对于学校我正在创建一个输入篮球比分的程序,我现在将它们添加到一个文本文档中,该文件位于名为" Scores.txt"的调试文件夹中,等等作为日期,积分,篮板等。有一个","在每个值之间,我打算让它按下按钮" btnPPG"这将从文本文件中获取一列,以便能够添加每个单独的值并将其除以分数的多少值(平均值),例如第一列保存日期,第二列中的点数补充日期在第二栏中,我没有这方面的知识,因为我对编码很新,并且似乎无法在互联网上找到类似的代码
答案 0 :(得分:0)
好的,我觉得应该有用..
函数ReadTextFromFile
打开您的文本文件并尝试读取它并将每个游戏添加到列表中。每个游戏应该是列表中的一个项目。
CalculateColumnAverage将以正确的格式迭代传递给它的任何列表,并计算列号中所有值的平均值。
Public Class Form1
Dim gamesList As List(Of String())
Dim ScoreAverage As Single
Private Sub BtnPPG_Click(sender As Object, e As EventArgs) Handles btnPPG.Click
gamesList = ReadTextFromFile("c:\Scores.txt")
'calculate the average of all the numbers in column 3
'change the number to which ever column is appropriate
'Don't forget that the first column is 0, the second is 1
'and so on
ScoreAverage = CalculateColumnAverage(gamesList, 3)
End Sub
Private Function ReadTextFromFile(filePath As String) As List(Of String())
Dim data As New List(Of String())
If File.Exists(filePath) Then
Using MyReader As New FileIO.TextFieldParser(filePath)
MyReader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
MyReader.Delimiters = New String() {","}
Dim currentRow As String()
'Loop through all of the fields in the file.
'If any lines are corrupt, report an error and continue parsing.
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
data.Add(currentRow)
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & " is invalid. Skipping")
End Try
End While
End Using
End If
Return data
End Function
Private Function CalculateColumnAverage(dataList As List(Of String()), column As Integer) As Single
Dim average As Single
Dim columnTotal As Integer
For Each game As String() In dataList
If IsNumeric(game(column)) Then
columnTotal = columnTotal + game(column)
Else
Throw New ArgumentOutOfRangeException("column", "Column " & column & " does exist")
End If
Next
average = columnTotal / dataList.Count
Return average
End Function
End Class