VB阵列错误等级书籍分配

时间:2013-11-06 08:29:41

标签: arrays vb.net

我的问题是当我输入四个测试的分数时:1 2 3 3,它计算总数和平均值一切都很好,但如果我把测试的分数大于3,这比我的数组大,那就给我错误在这个功能

Public Function TotalScore(studentScore() As Integer, intTotalScore As Integer) As Integer
    For Each i As Integer In studentScore
        intTotalScore += studentScore(i)
    Next
    Return intTotalScore
End Function 

错误消息是index is out of range array。 对不起,如果您需要额外的代码或更多细节,我不知道如何更好地解释它,我将非常乐意提供。谢谢你的时间

 Public g_intTotalScore As Integer                                                       'total score
 Public g_decAverageScore As Decimal                                                     'average score
 Public g_strLetterScore As String
 Public Const intMAX_SUBSCRIPT_STUDENTS_NAMES As Integer = 4                            'max subscript for students names 
 Public Const intMAX_SUBSCRIPT_SCORE As Integer = 3                                      'max subscript for student numeric scores on 4 test

Public strStudentsNames(intMAX_SUBSCRIPT_STUDENTS_NAMES) As String                 'array that holds students names
Public strLetterGrades() As String = {"A", "B", "C", "D", "F"}                     'array that hold letter grades
Public intStudent1(intMAX_SUBSCRIPT_SCORE) As Integer                              'hold test scores for student1

我创建的函数接受两个参数来计算4个测试的总分

Public Function TotalScore(studentScore() As Integer, intTotalScore As Integer) As Integer
    For Each i As Integer In studentScore
        intTotalScore += studentScore(i)
    Next
    Return intTotalScore
End Function

以下是学生姓名和4个考试成绩的输入

Do While intCount < strStudentsNames.Length
    'input data for student number1
    If intCount = 0 Then
        intCounter = 0
        strStudentsNames(intCount) = InputBox("Enter Student Name number" &       intCount + 1, "Enter Data")
        Do While intCounter < intStudent1.Length
            intStudent1(intCounter) = CInt(InputBox("Student Name: " & strStudentsNames(intCount) & vbCrLf &
                                                    "Enter Score for test number " & intCounter + 1, "Enter Data"))
            intCounter += 1
        Loop
    End If
    intCount += 1
Loop

这里是要列出的显示数据

'student1: calculate total , avaerage score, display average score, reset total score
g_intTotalScore = TotalScore(intStudent1, g_intTotalScore)
g_decAverageScore = Average(g_decAverageScore)
lstOutPut.Items.Add("Student Name: " & strStudentsNames(0) & " => The average score is: " & g_decAverageScore.ToString & " => Grade: ")
g_intTotalScore = 0

1 个答案:

答案 0 :(得分:0)

错误意味着您正在尝试从阵列中不存在的数组索引中获取内容。例如,数组有10个元素,从0到9索引,你调用索引号11。

尝试像这样使用每个:

For Each i As Integer In studentScore
        intTotalScore += i
Next