I have the following text file (ExamMarks.txt)
John, 85, 95, 90
Micheal, 60, 75, 75
I want to extract a line and take the Name and separately and the ints separately. Then I want to print the name and the average of the numbers like this in a label:
John's average is 90
Micheal's average is 70
So far I can only display what is in the text file in a label (see below):
Dim FILE_NAME As String = "C:\ExamMarks.txt"
Dim TextLine As String
If System.IO.File.Exists(FILE_NAME) = True Then
Dim objReader As New System.IO.StreamReader(FILE_NAME)
Do While objReader.Peek() <> -1
Te开发者_Go百科xtLine = TextLine & objReader.ReadLine & vbNewLine
Loop
lblResults.Text = TextLine
Else
MsgBox("File Does Not Exist")
End If
Any help is appreciated.
Do this processing for each of the lines in the file. It assumes that the name is always the first word in the string, then it calculates the average of all the numbers in the string.
'Split the test string on commas
Dim strScores() As String = strTest.Split(",".ToCharArray)
Dim strWord As String
Dim intTotalScore As Integer
Dim intCountOfScores As Integer
Dim intAverageScore As Integer
'Name is the first word in the line
strName = strScores(1).Trim
For Each strWord In strScores
If IsNumeric(strWord) Then
intTotalScore = intTotalScore + Int(strWord.Trim)
intCountOfScores = intCountOfScores + 1
End If
Next
'Calculate the average
intAverageScore = intTotalScore / intCountOfScores
You can do all this much more briefly with some more modern code:
- Use the built-in TextFieldParser to read the comma-separated file, and access each row as a string array. It's simpler and more robust than using
Split
. - And then use
IEnumerable
extension methods to calculate the average all in one line.
a. Skip(1) skips the first entry.
b. Average() lets you convert the remaining entries toDouble
and then take the average.
Like this:
Sub Main()
Using MyReader As New _
Microsoft.VisualBasic.FileIO.TextFieldParser("ExamMarks.txt")
MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters(",")
Dim currentRow As String()
While Not MyReader.EndOfData
Try
' Read row as an array of strings '
currentRow = MyReader.ReadFields()
' Calculate average '
Dim dAverage As Double = _
currentRow.Skip(1).Average(Function(s) Convert.ToDouble(s))
' Write out result '
Console.WriteLine(currentRow(0) & "'s average is " & _
Convert.ToString(dAverage))
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & "is not valid and will be skipped.")
End Try
End While
End Using
Console.ReadLine()
End Sub
精彩评论