线性搜索数组错误

时间:2017-12-14 13:00:38

标签: arrays vb.net for-loop if-statement procedure

我正在尝试实现线性搜索,但每当我转到linearSearch()子例程时,我都会收到错误:

  

索引超出了数组的范围

发出此错误的行是包含If list(a) = numberToFind Then的行。我该如何解决这个问题?

Module Module1

Sub Main()

    Dim list(99) As Integer
    Dim x As Integer = 0
    Dim answer As Integer

    Console.Write("Enter a value, type 9999 to stop.")
    answer = Console.ReadLine()

    For i = 0 To list.Length

        If answer = 9999 Then
            linearSearch(list)
        Else
            list(i) = answer
            Console.Write("Enter another")
            answer = Console.ReadLine

        End If
    Next

End Sub

Sub linearSearch(ByVal list)

    Dim numberToFind, comparisonNo As Integer
    comparisonNo = 0

    Console.Write("What number do you want to find?")
    numberToFind = Console.ReadLine()

    For a = 1 To list.Length
        If list(a) = numberToFind Then
            Console.Write(comparisonNo)
        Else
            comparisonNo += 1
        End If
    Next
    Console.ReadLine()
End Sub

End Module

1 个答案:

答案 0 :(得分:3)

将“For a = 1 To list.Length”更改为“For a = 0 To list.Length - 1”。数组基于零。