0

我有以下代码写入由 10 行分隔的三个等级逗号的 .txt 文件。(每一行看起来像这样,94,57,84,)这段代码可以很好地写入文件,但我不知道如何让它平均分数。我绝对需要它来平均放在文本框中的 30 个分数,但我希望它也能平均每一行。我的 GUI 在我手动运行程序时执行此操作,但在我拉入我制作的文本文件时不会执行此操作。这是我的代码。第一部分将是我编写的代码,第二部分将是我的所有代码。感谢您提供任何有用的建议。

这是直接来自书中的代码。我所做的只是添加两个按钮和最后两个按钮的代码。我还在类之前添加了 Import system IO 和 Dim 文件名的公共 dim 语句作为字符串。它会在没有差异的情况下写入,但是当我调用提交按钮时,它会在“grades(studentCount,0)=Concert.toInt32(test1TestBox.Text) 出现错误,所以我只从底部添加了数组代码行 3、4、5。不过,这给了我一个“0”的平均计算。这是直接来自书中的代码,除了显示和打开按钮代码

       Imports System.IO ' using classes from this namespace

Public Class GradeReport
Dim fileName As String ' name of file containing account data
Dim grades(9, 2) As Integer ' stores 10 students' grades on 3 tests
Dim studentCount As Integer = 0 ' number of students entered

' display heading in gradeListBox
Private Sub GradeReport_Load(sender As Object,
   e As EventArgs) Handles MyBase.Load
    ' headings row for gradesListBox
    gradesListBox.Items.Add(vbTab & vbTab & "Test 1" & vbTab &
       "Test 2" & vbTab & "Test 3" & vbTab & "Average")
End Sub

' process one student's grades
Private Sub submitButton_Click(sender As Object,
   e As EventArgs) Handles submitButton.Click

    ' retrieve the student's grades
    grades(studentCount, 0) = Convert.ToInt32(test1TextBox.Text)
    grades(studentCount, 1) = Convert.ToInt32(test2TextBox.Text)
    grades(studentCount, 2) = Convert.ToInt32(test3TextBox.Text)

    ' begin creating String containing the student's grades and average
    Dim output As String = "Student " & studentCount & vbTab

    ' append each test grade to the output
    For column = 0 To grades.GetUpperBound(1)
        ' if the Letter RadioButton is checked
        If letterRadioButton.Checked = True Then
            ' append letter grade to the output
            output &= vbTab & LetterGrade(grades(studentCount, column))
        Else
            ' append number grade to the output
            output &= vbTab & grades(studentCount, column)
        End If
    Next

    ' append the student's test average to the output
    output &= vbTab & CalculateStudentAverage(studentCount)

    gradesListBox.Items.Add(output) ' add output to the ListBox
    studentCount += 1 ' update number of students entered
    averageLabel.Text = CalculateClassAverage() ' display class average
    DisplayBarChart() ' display the current grade distribution

    ' clear the input TextBoxes and set focus to first TextBox
    test1TextBox.Clear()
    test2TextBox.Clear()
    test3TextBox.Clear()
    test1TextBox.Focus()

    ' limit number of students
    If studentCount = grades.GetUpperBound(0) + 1 Then
        inputGradesGroupBox.Enabled = False ' disable GroupBox's controls
    End If
End Sub ' submitButton_Click

' handles Numeric and Letter RadioButtons' CheckChanged events
Private Sub RadioButton_CheckedChanged(sender As Object,
   e As EventArgs) _
   Handles numericRadioButton.CheckedChanged,
      letterRadioButton.CheckedChanged

    ' if there are grades to display, call DisplayClassGrades
    If studentCount > 0 Then
        DisplayClassGrades()
    End If
End Sub ' RadioButton_CheckedChanged

' calculates a student's test average
Function CalculateStudentAverage(row As Integer) As String
    Dim gradeTotal As Integer = 0 ' student's total grade

    ' sum the grades for the student
    For column = 0 To grades.GetUpperBound(1)
        gradeTotal += grades(row, column)
    Next

    Dim studentAverage As String = String.Empty ' output string

    ' calculate the student's test average
    If letterRadioButton.Checked = True Then
        studentAverage =
           LetterGrade(gradeTotal / (grades.GetUpperBound(1) + 1))
    Else
        studentAverage = String.Format("{0:F}",
           (gradeTotal / (grades.GetUpperBound(1) + 1)))
    End If

    Return studentAverage ' return the student's average
End Function ' CalculateStudentAverage

' calculates the class average
Function CalculateClassAverage() As String
    Dim classTotal As Integer = 0 ' class's total grade

    ' loop through all rows that currently contain grades
    For row = 0 To studentCount - 1
        ' loop through all columns
        For column = 0 To grades.GetUpperBound(1)
            classTotal += grades(row, column) ' add grade to total
        Next column
    Next row

    Dim classAverage As String = String.Empty ' output string

    ' if the Letter RadioButton is checked, return letter grade
    If letterRadioButton.Checked = True Then
        classAverage = LetterGrade(classTotal /
           (studentCount * (grades.GetUpperBound(1) + 1)))
    Else ' return numeric grade
        classAverage = String.Format("{0:F}", (classTotal /
           (studentCount * (grades.GetUpperBound(1) + 1))))
    End If

    Return classAverage ' return the class average
End Function ' CalculateClassAverage

' determines a letter grade corresponding to a numeric grade
Function LetterGrade(grade As Double) As String
    Dim output As String ' the letter grade to return

    ' determine the correct letter grade
    Select Case grade
        Case Is >= 90
            output = "A"
        Case Is >= 80
            output = "B"
        Case Is >= 70
            output = "C"
        Case Is >= 60
            output = "D"
        Case Else
            output = "F"
    End Select

    Return output ' return the letter grade
End Function ' LetterGrade

' display the grades for all students entered
Sub DisplayClassGrades()
    gradesListBox.Items.Clear() ' clear the ListBox

    ' add the header to the ListBox
    gradesListBox.Items.Add(vbTab & vbTab & "Test 1" & vbTab &
       "Test 2" & vbTab & "Test 3" & vbTab & "Average")

    ' loop through all the rows
    For row = 0 To studentCount - 1
        Dim output As String = "Student " & row & vbTab

        ' loop through all the columns
        For column = 0 To grades.GetUpperBound(1)
            If letterRadioButton.Checked = True Then
                ' add letter grade to output string
                output &= vbTab & LetterGrade(grades(row, column))
            Else
                ' add number grade to output string
                output &= vbTab & (grades(row, column))
            End If
        Next column

        ' add the student's average to the output
        output &= vbTab & CalculateStudentAverage(row)

        ' add the output to the ListBox
        gradesListBox.Items.Add(output)
    Next row

    ' update the class average
    averageLabel.Text = CalculateClassAverage()
End Sub ' DisplayClassGrades

' display a bar chart of the grade distribution
Sub DisplayBarChart()
    barChartListBox.Items.Clear() ' remove current items

    ' stores frequency of grades in each range of 10 grades
    Dim frequency(10) As Integer

    ' for each grade, increment the appropriate frequency
    For row = 0 To studentCount - 1
        For column = 0 To grades.GetUpperBound(1)
            frequency(grades(row, column) \ 10) += 1
        Next column
    Next row

    ' for each grade frequency, display bar of asterisks
    For count = 0 To frequency.GetUpperBound(0)
        Dim bar As String ' stores the label and bar

        ' create bar label ( "00-09: ", ..., "90-99: ", "100: " )
        If count = 10 Then
            bar = String.Format("{0, 5:D}: ", 100)
        Else
            bar = String.Format("{0, 2:D2}-{1, 2:D2}: ",
               count * 10, count * 10 + 9)
        End If

        ' append bar of asterisks
        For stars = 1 To frequency(count)
            bar &= ("*")
        Next

        barChartListBox.Items.Add(bar) ' display bar
    Next count
End Sub ' DisplayBarChart

Private Sub Open_Click(sender As Object, e As EventArgs) Handles Open.Click

    ' opens a file in which accounts are stored

    Dim result As DialogResult ' stores result of Open dialog

    ' create dialog box enabling user to open file
    Using fileChooser As New OpenFileDialog()
        result = fileChooser.ShowDialog()
        fileName = fileChooser.FileName ' get specified file name
    End Using ' automatic call to fileChooser.Dispose() occurs here

    ' if user did not click Cancel, enable Buttons
    If result <> Windows.Forms.DialogResult.Cancel Then
        Display.Enabled = True

    End If
End Sub ' OpenToolStripMenuItem_Click


Private Sub Display_Click(sender As Object, e As EventArgs) Handles Display.Click

    ' display accounts of specified type

    Dim fileReader As StreamReader = Nothing

    ' read and display file information
    Try
        gradesListBox.Text = "The accounts are:" & vbCrLf

        ' open file for reading
        fileReader = New StreamReader(fileName)

        ' read file and display lines that match the balance type
        Do While Not fileReader.EndOfStream ' while not end of file
            Dim line As String = fileReader.ReadLine() ' read line
            Dim fields() As String = line.Split(","c) ' split into fields
            'Dim fields() As String = line.Split(CChar(","))

            ' get data from fields array

            Dim Test1 As String = fields(0)             'Integer = Convert.ToInt32(fields(0))
            Dim Test2 As String = fields(1)
            Dim Test3 As String = fields(2)

            ' If ShouldDisplay(balance, accountType) Then
            gradesListBox.Items.Add(vbTab & vbTab & Test1 & vbTab &
               Test2 & vbTab & Test3 & vbCrLf)

        Loop
    Catch ex As IOException
        MessageBox.Show("Cannot Read File", "Error",
           MessageBoxButtons.OK, MessageBoxIcon.Error)
    Finally ' ensure that file gets closed
        If fileReader IsNot Nothing Then
            Try
                fileReader.Close() ' close StreamReader
            Catch ex As IOException
                MessageBox.Show("Error closing file", "Error",
                   MessageBoxButtons.OK, MessageBoxIcon.Error)
            End Try
        End If
    End Try


    ' submitButton.PerformClick


    studentCount += 1 ' update number of students entered
    averageLabel.Text = CalculateClassAverage() ' display class average
    DisplayBarChart() ' display the current grade distribution



End Sub ' submitButton_Click

结束班级'成绩报告

4

1 回答 1

0

您的老师可能意味着文件中的数据仅被显示而不被存储。看看这样的事情是否有帮助:

Private Sub Display_Click(sender As Object, e As EventArgs) Handles Display.Click

    ' display accounts of specified type

    Dim fileReader As StreamReader = Nothing

    ' read and display file information
    Try
        gradesListBox.Text = "The accounts are:" & vbCrLf

        ' open file for reading
        fileReader = New StreamReader(fileName)

        ' read file and display lines that match the balance type
        Dim Counter As Integer = 0
        Do While Not fileReader.EndOfStream ' while not end of file
            Dim line As String = fileReader.ReadLine() ' read line
            Dim fields() As String = line.Split(","c) ' split into fields
            'Dim fields() As String = line.Split(CChar(","))

            ' get data from fields array

            For I = 0 To 2
                Grades(Counter,I) = Integer.Parse(fields(I))
            Next


            ' If ShouldDisplay(balance, accountType) Then
            gradesListBox.Items.Add(vbTab & vbTab & Grades(Counter,0) & vbTab &
               Grades(Counter,1) & vbTab & Grades(Counter,2) & vbCrLf)
            If Counter <= 8 Then
                 Counter += 1
            Else
               Exit Do
            End If
        Loop
    Catch ex As IOException
        MessageBox.Show("Cannot Read File", "Error",
           MessageBoxButtons.OK, MessageBoxIcon.Error)
    Finally ' ensure that file gets closed
        If fileReader IsNot Nothing Then
            Try
                fileReader.Close() ' close StreamReader
            Catch ex As IOException
                MessageBox.Show("Error closing file", "Error",
                   MessageBoxButtons.OK, MessageBoxIcon.Error)
            End Try
        End If
    End Try


    ' submitButton.PerformClick


    studentCount += 1 ' update number of students entered
    averageLabel.Text = CalculateClassAverage() ' display class average
    DisplayBarChart() ' display the current grade distribution



End Sub ' submitButton_Click

当然,这只会将数组填充到您设置的大小。如果您希望数据更加动态,请改用 List(Of)。

这也假设文件中的数据是高度一致的并且不验证数据。

于 2013-11-04T03:27:51.387 回答