Reading more than one integer on a line in a listbox

纵然是瞬间 提交于 2019-12-13 08:54:55

问题


So I have a button which reads a file, and puts the contents of that file into a list box. When I press the button this is what is shows:

Jim 6 8 9

Tim 7 5 6

Bill 4 10 8

What I want to do is make a separate button which adds each of the person's scores and then finds the average of them. Once it has calculated the average of the person then I want the average to be in the place of the 3 scores.

The code that I have at the moment only takes the first score of each person and then adds all of them and shows the result in a messagebox.

This is my code at the moment:

Dim scorevalues As New List(Of Integer)
    For Each line As String In System.IO.File.ReadLines(file1)
        Dim scores As System.Text.RegularExpressions.Match = System.Text.RegularExpressions.Regex.Match(line, "\d+")
        If scores.Success Then
            scorevalues.Add(Convert.ToInt32(scores.Value))
        End If
    Next
    listbox1.DataSource = scorevalues

    Dim Scoretots As Integer = 0

    For scores2 = 0 To listbox1.Items.Count - 1
        Scoretots = Scoretots + listbox.Items(scores2)
    Next
    MessageBox.Show("Total: " & Scoretots.ToString)

This is what my code produces:

6

7

4

And then a messagebox shows 28


回答1:


This will get you going. It's the same as this question https://stackoverflow.com/questions/29902255/working-out-averages-of-numbers-in-a-list-box-line/29902583#29902583

Sub Main()
    Dim scores As String = "Bill 10 9 8"
    Dim score As System.Text.RegularExpressions.MatchCollection = System.Text.RegularExpressions.Regex.Matches(scores, "\d+")

    Dim sum As Integer = 0
    For i As Integer = 0 To score.Count - 1
        sum += Convert.ToInt32(score.Item(i).Value)
        Console.WriteLine(score.Item(i).Value)
    Next
    Dim average = sum / score.Count
    Console.WriteLine("Average: {0}", average)

    Console.ReadLine()
End Sub

Results:




回答2:


I believe your main problem is that your regex call is only catching the first match. Change the variable "scores" to a MatchCollection and use the Matches function of the regex function. Then, you can use For...Each to parse through the matches and add them to the list, compute your averages, etc.



来源:https://stackoverflow.com/questions/29905092/reading-more-than-one-integer-on-a-line-in-a-listbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!