在列表框中的一行中读取多个整数

Reading more than one integer on a line in a listbox

所以我有一个按钮可以读取文件,并将该文件的内容放入列表框中。当我按下按钮时,显示的是:

吉姆 6 8 9

蒂姆 7 5 6

账单 4 10 8

我想做的是制作一个单独的按钮,将每个人的分数相加,然后求出它们的平均值。一旦它计算出该人的平均值,那么我希望平均值代替 3 个分数。

我目前的代码只取每个人的第一个分数,然后将所有分数相加并在消息框中显示结果。

这是我目前的代码:

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)

这是我的代码生成的结果:

6

7

4

然后一个消息框显示 28

我认为您的主要问题是您的正则表达式调用仅捕捉到第一个匹配项。 将变量 "scores" 更改为 MatchCollection 并使用正则表达式函数的 Matches 函数。 然后,您可以使用 For...Each 来解析匹配项并将它们添加到列表中,计算平均值等。

这会让你继续前进。和这个问题一样

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

结果: