在VB.net中汇总.txt文件数组的元素

时间:2013-03-08 21:29:47

标签: arrays vb.net average

高级VB课程的大学生正在寻求帮助的论坛 - 我已经找到了一些代码示例,但我很难搞清楚这一个......任何和所有帮助都表示赞赏:)

此应用程序导入存储在bin,debug文件夹中的.txt文件,名为data.txt ..20记录,每条记录3行,最后一行是学生的成绩,我需要通过将每个记录等级相加并除以20然后显示在显示平均值的lstbox上来平均成绩。

到目前为止我已经......

    Dim objReader As IO.StreamReader
    Dim intFill As Integer
    Dim intCount As Integer = 0
    Dim intAverage As Integer
    Dim strLocationAndNameOfFile As String = "data.text"

    If IO.File.Exists(strLocationAndNameOfFile) = True Then
        objReader = IO.File.OpenText(strLocationAndNameOfFile)
    Else
        MsgBox("The file is not available. Restart the program when the file is avilable", , "Error")
        Me.Close()
    End If

    If IO.File.Exists(strLocationAndNameOfFile) Then
        objReader = IO.File.OpenText(strLocationAndNameOfFile)
        Do While objReader.Peek <> -1
            _strName(intCount) = Convert.ToString(objReader.ReadLine())
            _strItemID(intCount) = Convert.ToString(objReader.ReadLine())
            _intGrade(intCount) = Convert.ToInt32(objReader.ReadLine())
            intCount += 1
        Loop
        objReader.Close()
    End If

    For intFill = 0 To (_strName.Length - 1)
        *'intAverage = SUM OF ALL AVERAGES / LENGTH OF ARRAY -1*
        Me.lstAverage.Items.Add(intAverage.ToString())

2 个答案:

答案 0 :(得分:1)

循环读取等级时总结了它们

    Dim total as Integer
    Do While objReader.Peek <> -1
        _strName(intCount) = Convert.ToString(objReader.ReadLine())
        _strItemID(intCount) = Convert.ToString(objReader.ReadLine())
        _intGrade(intCount) = Convert.ToInt32(objReader.ReadLine())
        total += _intGrade(intCount)
        intCount += 1
    Loop

然后除以20或_intGrade.Length

    intAverage = total / _intGrade.Length

答案 1 :(得分:1)

这么多问题,就像我讨厌做其他人的作业一样,我希望你能看到它看起来像什么

Public Function GetAverageGrade(ByVal filename As String) As Double
    Dim totalGrade As Integer = 0
    Dim lineCount As Integer = 0
    Dim line As String

    Using rdr As New IO.StreamReader(filename)
       While (line = rdr.ReadLine()) IsNot Nothing
           lineCount += 1
           If lineCount Mod 3 = 0 Then totalGrade += Convert.ToInt32(line)
       End While
    End Using
    Return totalGrade / (lineCount / 3.0)
End Function

当然,您可能希望使用该数据做更多事情,而不仅仅是获得平均成绩。因此,更好的选择是构建代码,将其作为一组记录读取:

Public Class GradeItem
    Public Property Name As String
    Public Property Item As String
    Public Property Grade As Integer
End Class

然后

Public Iterator Function ReadGradeItems(ByVal fileName As String) As IEnumerable(Of GradeItem)
    Using rdr As New IO.StreamReader(fileName)
        While rdr.Peek() <> -1
            Yield New GradeItem With {.Name = rdr.ReadLine(), .Item= rdr.ReadLine(), .Grade = Convert.ToInt32(rdr.ReadLine()}
        End While
    End Using
End Function

现在把它们放在一起:

Dim grades As IEnumerable(Of GradeItem) = ReadGradeItems("data.text")

lstAverage.Items.Add(grades.Select(Function(g) g.Grade).Average())