2017-12-14 5 views
-1

Ich versuche, eine lineare Suche zu implementieren, aber wenn ich auf die linearSearch() Unterprogramm weitergehen, erhalte ich die Fehlermeldung:Linear Array Search Fehler

Index was outside the bounds of the array

Die Linie diesen Fehler gibt, ist das ein If list(a) = numberToFind Then enthält. Wie kann ich das beheben?

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 

Antwort

3

Ändern Sie die Zeilen "Für a = 1 Um List.length" auf "Für a = 0 Um List.length - 1". Arrays sind nullbasiert.