brownmamba
brownmamba

Reputation: 13

Adding Item to Array (VB 2008)

The objective of the program is to interpret hockey statistics from a file using StreamReader and then display an added column of points. The following code kinda does so, however it’s ineffective in the sense that it doesn’t add the points value to the array - it separately outputs it. Looking for assistance as to how it would be possible to incorporate the points value into 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

Upvotes: 1

Views: 102

Answers (3)

Joel Coehoorn
Joel Coehoorn

Reputation: 415790

VS2008 is ancient, especially when later versions of Visual Studio are free. I felt like showing an implementation using more-recent code. Like others, I strongly support building a class for this. The difference is my class is a little smarter, using the Factory pattern for creating instances and a Property to compute Points as needed:

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()

I was gonna give you VS 2008 version afterward, but looking at this, the only thing here you couldn't do already even by VS 2010 was string interpolation... you really should upgrade.

Upvotes: 1

Mary
Mary

Reputation: 15091

Parallel arrays are really not the way to handle this. Create a class or structure to organize the data. Then create a list of the class. The list can be set as the DataSource of a DataGridView which will display your data in nice columns with headings matching the names of your properties in the Hockey class. You can easily order your data in the HockeyList by any of the properties of Hockey.

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

Upvotes: 0

Andrew Mortimer
Andrew Mortimer

Reputation: 2370

This should get you pretty close:

It'll need extra validation. It doesn't take into account whatever value you have between the name and the goals.

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

Upvotes: 1

Related Questions