【发布时间】:2016-04-20 02:20:15
【问题描述】:
我在尝试使用线性搜索来查找用户在数组中输入的名称时遇到此错误。这是我声明数组并获取输入的时候。
Public Const SIZE_ARRAY = 9
Public Sub cmdStart_Click(sender As Object, e As EventArgs) Handles cmdStart.Click
Dim myArray(SIZE_ARRAY) As String
Dim index As Integer
Public Sub cmdStart_Click(sender As Object, e As EventArgs) Handles cmdStart.Click
Dim count As Integer = 0
For Me.index = 0 To SIZE_ARRAY
myArray(index) = InputBox("Enter a name, Enter a name")
count = count + 1
Next
If count = 10 Then
lblInstructions.Visible = False
cmdStart.Visible = False
lblInstructions2.Visible = True
txtSearch.Visible = True
lblOutput.Visible = True
cmdSearch.Visible = True
End If
End Sub
这里是我使用线性搜索的地方。
Public Sub cmdSearch_Click(sender As Object, e As EventArgs) Handles cmdSearch.Click
Dim found As Boolean
Dim name As String
name = txtSearch.Text
found = LinearSearch(myArray, Val(name))
If found Then
lblOutput.Text = name & " was found at cell " & index
Else
lblOutput.Text = name & " was not found"
End If
End Sub
这里是线性搜索函数
Public Function LinearSearch(ByVal list() As Integer, ByVal searchValue As Integer) As Boolean
Dim found As Boolean = False
Dim index As Integer
While found = False And index <= UBound(list)
If list(index) = searchValue Then
found = True
Else
index += 1
End If
End While
Return found
End Function
【问题讨论】:
-
错误信息的哪一部分你不明白?
-
就像一个小注释 - 在让用户输入名称的 Sub 中 - 在循环结束后,
count变量将始终等于 10。围绕后续代码块的If..End If语句是不必要的。 - 干杯 -
另外 - 抱歉 - 我注意到您想在 cmdSearc_click 子程序中使用
index来显示名称的找到位置。但是,LinearSearch子中的index变量 - 尽管它具有相同的名称,但不是同一个变量。所以你不会从线性搜索中得到正确的索引。
标签: arrays vb.net visual-studio linear-search