如何修复“索引超出了数组的范围”

时间:2017-08-22 12:09:37

标签: vb.net

我有错误

  

索引超出了数组的范围。

我想在vb.net上实现算法插值搜索。

这是我的代码:

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Dim NameArray(6) As String
    Dim lo As Integer
    Dim hi As Integer
    Dim searchName As String
    Dim FoundIt As Boolean
    Dim middle As Integer
    Dim position As Integer

    NameArray(1) = TextBox1.Text
    NameArray(2) = TextBox2.Text
    NameArray(3) = TextBox3.Text
    NameArray(4) = TextBox4.Text
    NameArray(5) = TextBox5.Text
    NameArray(6) = TextBox6.Text
    searchName = TextBox7.Text
    lo = 1
    hi = NameArray.Length
    FoundIt = False

    'vb.net function to sort elements in an array alphabetically and write the back in the correct order
    Array.Sort(NameArray)
    TextBox1.Text = NameArray(1)
    TextBox2.Text = NameArray(2)
    TextBox3.Text = NameArray(3)
    TextBox4.Text = NameArray(4)
    TextBox5.Text = NameArray(5)
    TextBox6.Text = NameArray(6)

    Do
        middle = lo + ((CDbl(hi - lo) / (NameArray(hi) - NameArray(lo))) * (searchName - NameArray(lo)))
        If NameArray(middle) = searchName Then
            FoundIt = True
            position = middle
        Else
            If NameArray(middle) < searchName Then
                lo = middle + 1
            Else
                hi = middle - 1
            End If
        End If
    Loop While Not FoundIt And lo <= hi
    If FoundIt = True Then
        TextBox9.Text = "found at position" & CDbl(position)
    End If
End Sub

0 个答案:

没有答案