为什么我在尝试引用arrray元素时出错?

时间:2015-12-16 09:14:27

标签: .net vb.net

如何引用数组元素。我现在尝试使用0,1,2,3,4,但它会重新抛出

  

“IndexOutOfRangeException”

Dim IndividualResults As String() = results.Split(New Char() {";"})
            For Each IndividualResult In IndividualResults
                Dim words As String() = IndividualResult.Split(New Char() {","})
                strStudentFirstName = words(0)
                strStudentLastName = words(1)

                intScore1 = CInt(words(2))
                intHighestScore = intScore1

                intScore2 = CInt(words(3))
                If intScore2 > intHighestScore Then
                    intHighestScore = intScore2
                End If

                intScore3 = CInt(words(4))
                If intScore3 > intHighestScore Then
                    intHighestScore = intScore3
                End If

1 个答案:

答案 0 :(得分:0)

如果您处理数组中未知数量的元素,这可能是一个更安全的选择

Private Sub testSplits()
    Dim results As String = "James,Jones,1;Julie,Bond,2,3;Eric,Haskell,4,5,6;;"
    splitValues(results)
End Sub

Private Sub splitValues(results As String)

    Dim strStudentFirstName As String
    Dim strStudentLastName As String

    Dim IndividualResults As String() = results.Split(Convert.ToChar(";"))
    For Each IndividualResult As String In IndividualResults

        Dim words As String() = IndividualResult.Split(Convert.ToChar(","))
        Dim wordCount As Integer = words.GetUpperBound(0)

        If wordCount > 0 Then

            strStudentFirstName = words(0)
            strStudentLastName = words(1)

            Dim scores As New List(Of Integer)
            If wordCount >= 2 Then
                scores.Add(CInt(words(2)))
            End If
            If wordCount >= 3 Then
                scores.Add(CInt(words(3)))
            End If
            If wordCount > 3 Then
                scores.Add(CInt(words(4)))
            End If

            Dim highestScore As Integer = scores.Max()

            Debug.Print(String.Concat("Student ", strStudentFirstName, " ", strStudentLastName, " : Highest score: ", highestScore))

        End If

    Next

End Sub