.net 如何写入数组并执行计算
我在一个.txt文件中编写了以下代码,该文件有三个等级,逗号由10行分隔。(每一行看起来像这样,94,57,84,)这段代码在文件中写起来很好,但我不知道如何使它平均分数。我肯定需要它来平均30分,是放在一个文本框,但我想它平均每行以及。我的GUI在我手动运行程序时执行此操作,但在我拉入生成的文本文件时不执行此操作。这是我的密码。第一部分是我编写的代码,第二部分是我所有的代码。谢谢你的建议 这是本书中的代码。我所做的只是添加了两个按钮,并在最后为这两个按钮编写了代码。我还将导入系统IO添加到类之前,并将dim filename的公共dim语句作为字符串添加。它将在没有差异的情况下写入,但当我调用submitbutton时,它在“grades(studentCount,0)=Concert.toInt32(test1TestBox.Text)处出现错误,因此我只从底部添加了数组代码行3,4,5。这使我的平均计算值为“0”。下面是本书中的代码,除了显示和打开按钮代码之外.net 如何写入数组并执行计算,.net,vb.net,.net,Vb.net,我在一个.txt文件中编写了以下代码,该文件有三个等级,逗号由10行分隔。(每一行看起来像这样,94,57,84,)这段代码在文件中写起来很好,但我不知道如何使它平均分数。我肯定需要它来平均30分,是放在一个文本框,但我想它平均每行以及。我的GUI在我手动运行程序时执行此操作,但在我拉入生成的文本文件时不执行此操作。这是我的密码。第一部分是我编写的代码,第二部分是我所有的代码。谢谢你的建议 这是本书中的代码。我所做的只是添加了两个按钮,并在最后为这两个按钮编写了代码。我还将导入系统IO添加到类之
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
使用来自此命名空间的类导入System.IO'
公开课成绩报告
Dim fileName作为包含帐户数据的文件的字符串名称
将分数(9,2)作为整数“存储10名学生在3次测试中的分数”
Dim studentCount为整数=0'输入的学生数
'在分级列表框中显示标题
私有子等级报告加载(发送者作为对象,
e作为EventArgs)处理MyBase.Load
'成绩列表框的标题行
gradesListBox.Items.Add(vbTab和vbTab&“测试1”和vbTab&
“测试2”&vbTab和“测试3”&vbTab和“平均值”)
端接头
“处理一名学生的成绩
私有子提交按钮单击(发送者作为对象,
e作为事件参数)处理submitButton。单击
'检索学生的成绩
成绩(studentCount,0)=转换为32(test1TextBox.Text)
成绩(studentCount,1)=转换为32(test2TextBox.Text)
成绩(学生人数,2)=转换为32(test3TextBox.Text)
'开始创建包含学生成绩和平均成绩的字符串
将输出设置为String=“Student”&studentCount&vbTab
'将每个测试等级附加到输出
对于列=0到坡度。GetUpperBound(1)
'如果选中了字母单选按钮
如果letterRadioButton.Checked=True,则
'将字母级别附加到输出
输出&=vbTab和LetterGrade(成绩(学生人数,列))
其他的
'将数字等级附加到输出
输出&=vbTab和成绩(学生人数,列)
如果结束
下一个
'将学生的测试平均值附加到输出
输出&=vbTab&CalculateStudentAverage(studentCount)
gradesListBox.Items.Add(输出)'将输出添加到列表框
studentCount+=1'更新输入的学生数
averageLabel.Text=CalculateClassAverage()'显示类平均值
DisplayBarChart()'显示当前等级分布
'清除输入文本框并将焦点设置为第一个文本框
test1TextBox.Clear()
test2TextBox.Clear()
test3TextBox.Clear()
test1TextBox.Focus()
“限制学生人数
如果studentCount=grades.GetUpperBound(0)+1,则
inputGradesGroupBox.Enabled=False“禁用GroupBox的控件
如果结束
结束子“提交”按钮单击
“处理数字和字母单选按钮”CheckChanged事件
私用子单选按钮\u CheckedChanged(发送者作为对象,
e作为事件参数)_
处理numericRadioButton.CheckedChanged,
letterRadioButton.CheckedChanged
'如果要显示等级,请调用DisplayClassGrades
如果studentCount>0,则
DisplayClassGrades()
如果结束
“结束子”单选按钮已选中已更改
'计算学生的平均考试成绩
函数将culatestudentaverage(行作为整数)计算为字符串
Dim gradeTotal为整数=0'学生的总成绩
“给学生加总分数
对于列=0到坡度。GetUpperBound(1)
成绩合计+=成绩(行、列)
下一个
Dim studentAverage As String=String.Empty“输出字符串
'计算学生的平均考试成绩
如果letterRadioButton.Checked=True,则
学生平均=
字母等级(总等级/(等级.上界(1)+1))
其他的
studentAverage=String.Format(“{0:F}”,
(gradeTotal/(grades.GetUpperBound(1)+1)))
如果结束
Return studentAverage'返回学生的平均值
结束函数“CalculateStudentAverage”
'计算班级平均数
函数CalculateClassAverage()作为字符串
Dim classTotal作为整数=0'类的总成绩
'循环浏览当前包含等级的所有行
对于行=0到studentCount-1
'循环遍历所有列
对于列=0到坡度。GetUpperBound(1)
classTotal+=等级(行、列)'将等级添加到总等级
下一栏
下一排
Dim classAverage As String=String.Empty“输出字符串
'如果选中字母单选按钮,则返回字母等级
如果letterRadioButton.Checked=True,则
类别平均=字母等级(类别总数)/
(学生人数*(grades.GetUpperBound(1)+1)))
Else返回数值等级
classAverage=String.Format(“{0:F}”,(classTotal)/
(学生人数*(grades.GetUpperBound(1)+1)))
如果结束
Return classAverage'返回类平均值
结束函数“计算平均值”
'确定与数字等级相对应的字母等级
函数LetterGrade(级别为双精度)作为字符串
将输出设置为字符串“要返回的字母等级”
'确定正确的字母等级
选择案例等级
案例>=90
输出=“A”
案例>=80
输出=“B”
案例>=70
输出=“C”
案例>=60
输出=“D”
其他情况
输出=“F”
EN
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