【问题标题】:Adding Item to Array (VB 2008)将项目添加到数组 (VB 2008)
【发布时间】:2018-12-22 18:14:52
【问题描述】:

该程序的目标是使用 StreamReader 解释文件中的曲棍球统计数据,然后显示添加的点列。下面的代码有点这样做,但是它没有将点值添加到数组中的意义上是无效的 - 它单独输出它。寻求有关如何将点值合并到 aryTextFile() 中的帮助;

    Dim hockeyFile, LineOfText, aryTextFile() As String
    Dim i As Integer
    Dim nameText(), NumberText(), goalsText(), assistsText(), GamesWonText() As String
    Dim IntAssists(), IntGoals(), PointsText() As Single

    hockeyFile = "C:\Users\Bob\Downloads\hockey.txt" 'state location of file

    Dim objReader As New System.IO.StreamReader(hockeyFile) 'objReader can read hockeyFile


    For i = 0 To objReader.Peek() <> -1 'reads each line seperately, ends when there is no more data to read
        LineOfText = objReader.ReadLine 'stores seperate lines of data in HockeyFile into LineofText  
        aryTextFile = LineOfText.Split(",") 'takes lines and converts data into array
        Name = aryTextFile(0) 'first piece of data in lines of text is the name 
        nameText(i) = aryTextFile(0)
        If nameText(0) = "Name" Then
            TextBox1.Text = LineOfText & ", Points." & vbCrLf 'displays first line fo text and adds "Points" label
        End If

        If Name <> "Name" Then 'when second line starts, then begin to intepret data
            NumberText(i) = aryTextFile(1)
            assistsText(i) = aryTextFile(2) 'assists are in third value of array 
            goalsText(i) = aryTextFile(3) 'goals are in fourth value of array
            GamesWonText(i) = aryTextFile(4)

            IntAssists(i) = Val(assistsText(i)) 'since our assists value is a string by default, it must be converted to a integer

            IntGoals(i) = Val(goalsText(i)) 'since our goals value is a string by default, it must be converted to a integer

            PointsText(i) = (IntGoals(i) * 2) + (IntAssists(i)) 'goals are two points, assists are one point


            TextBox1.Text = TextBox1.Text & NumberText(i) & assistsText(i) & goalsText(i) & GamesWonText(i) & PointsText(i) & vbCrLf 'Displays points as last value in each line

        End If
    Next i

【问题讨论】:

  • 你能在输入文件中显示一个数据行的样本吗?

标签: arrays vb.net


【解决方案1】:

这应该让你非常接近:

它需要额外的验证。它没有考虑您在名称和目标之间的任何价值。

Private Sub ProcessHockeyStats()

    Try

        Dim inputFile As String = "c:\temp\hockey.txt"
        Dim outputFile As String = "c:\temp\output.txt"

        If Not File.Exists(inputFile) Then
            MessageBox.Show("Missing input file")
            Return
        End If

        If File.Exists(outputFile) Then
            File.Delete(outputFile)
        End If

        Dim lines() As String = File.ReadAllLines(inputFile)

        Dim output As List(Of String) = New List(Of String)

        Dim firstLine As Boolean = True

        For Each line As String In lines

            Dim values() As String = line.Split(","c)
            Dim points As Integer

            If firstLine Then
                output.Add("Name, Assists, Goals, Points")
                firstLine = False
            Else
                'needs validation for values
                points = CInt(values(1) * 2) + CInt(values(2))
                output.Add(String.Concat(line, ",", points))
            End If

        Next

        File.WriteAllLines("c:\temp\outfile.txt", output)

    Catch ex As Exception
        MessageBox.Show(String.Concat("Error occurred: ", ex.Message))
    End Try

End Sub

【讨论】:

  • 感谢您的宝贵时间。有一个快速的问题 - 我注意到您将输出声明为列表。有什么办法可以直接将我已经拥有的数组转换为列表?
  • Dim testNewList As List(Of String) = New List(Of String) testNewList.AddRange(lines)
  • Catch ex As Exception 这段代码有什么作用?
【解决方案2】:

VS2008 是古老的,尤其是当 Visual Studio 的更高版本免费时。我想展示一个使用更新的代码的实现。和其他人一样,我强烈支持为此创建一个类。不同之处在于我的班级更聪明一点,使用工厂模式创建实例,并根据需要使用属性计算Points

Public Class HockeyPlayer
    Public Property Name As String
    Public Property Number As String
    Public Property Assists As Integer
    Public Property Goals As Integer
    Public Property Wins As Integer

    Public ReadOnly Property Points As Integer
        Get
           Return (Goals * 2) + Assists
        End Get
    End Property

    Public Shared Function FromCSVLine(line As String) As HockeyPlayer
         Dim parts() As String = line.Split(",")
         Return New HockeyPlayer With {
              .Name = parts(0),
              .Number = parts(1),
              .Assists = CInt(parts(2)),
              .Goals = CInt(parts(3)),
              .Wins = CInt(parts(4))
         }
    End Function
End Class

Dim hockeyFile As String = "C:\Users\Bob\Downloads\hockey.txt"

Dim players = File.ReadLines(hockeyFile).Skip(1).
             Select(Function(line) HockeyPlayer.FromCSVLine(line)).
             ToList() 'ToList() is optional, but I included it since you asked about an array

Dim result As New StringBuilder("Name, Number, Assists, Goals, Wins, Points")
For Each player In players
      result.AppendLine($"{player.Name}, {player.Number}, {player.Assists}, {player.Goals}, {player.Wins}, {player.Points}")
Next player

TextBox1.Text = result.ToString()

之后我打算给你 VS 2008 版本,但看看这个,你在 VS 2010 之前唯一不能做的就是字符串插值......你真的应该升级。

【讨论】:

  • 我正在做的事情需要使用VB 2008。我们还没有被介绍给类;这个特定的任务需要使用 StreamEReader/Writer 和数组,因此我发现它非常具有挑战性。有什么办法可以使我发布的代码工作?
【解决方案3】:

并行数组确实不是处理这个问题的方法。创建一个类或结构来组织数据。然后创建一个类的列表。该列表可以设置为DataGridViewDataSource,它将在漂亮的列中显示您的数据,其标题与您在Hockey 类中的属性名称匹配。您可以通过 Hockey 的任何属性轻松地对 HockeyList 中的数据进行排序。

Public Class Hockey
    Public Property Name As String
    Public Property Number As String
    Public Property Goals As Integer
    Public Property Assists As Integer
    Public Property Points As Integer
    Public Property GamesWon As Integer
End Class

Private HockeyList As New List(Of Hockey)

Private Sub FillListAndDisplay()            
    Dim path = "C:\Users\Bob\Downloads\hockey.txt"
    Dim Lines() = File.ReadAllLines(path)
    For Each line As String In Lines
        Dim arr() = line.Split(","c)
        Dim h As New Hockey()
        h.Name = arr(0)
        h.Number = arr(1)
        h.Assists = CInt(arr(2).Trim)
        h.Goals = CInt(arr(3).Trim)
        h.GamesWon = CInt(arr(4).Trim)
        h.Points = h.Goals * 2 + h.Assists
        HockeyList.Add(h)
     Next
     Dim orderedList = (From scorer In HockeyList Order By scorer.Points Ascending Select scorer).ToList 
     DataGridView1.DataSource = orderedList
End Sub

【讨论】:

    猜你喜欢
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-16
    • 2015-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多