Reading from text file and storing into an array

czeslaw1

Member
Joined
May 18, 2009
Messages
18
Programming Experience
Beginner
Hi, I am given a problem where I have a text file that contains the following:

12AVX
5
23ABC
8.97
23TWT
4.69
34ZAB
12.5
91BAN
34.67


Some of the instructions include "Define a structure named Product. The structure should contain two member variables: a String variable to store the item number and a Double variable to store the price" and "Declare a class-level array that contains five Product structure variables."

I am stuck on the following "The form’s Load event procedure should read the item numbers and prices from the ItemInfo.txt fi le and store them in the classlevel array. It also should add the item numbers to the list box."

Option Explicit On
Option Strict On
Option Infer Off

Public Class frmMain

    Private ProductInfo(4) As Product

    Structure Product
        Public strId As String
        Public dblPrice As Double
    End Structure

    Private Sub btnExit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExit.Click
        Me.Close()
    End Sub

    Private Sub frmMain_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Dim inFile As IO.StreamReader
        Dim intArray As Integer
        Dim intLength As Integer
        Dim strTemp As String

        ' verify that the file exists
        If IO.File.Exists("ItemInfo.txt") = True Then
            ' open the file for input
            inFile = IO.File.OpenText("ItemInfo.txt")
            'process loop instructions until end of

            Do Until inFile.Peek = -1
                strTemp = inFile.ReadLine
                Integer.TryParse(strTemp, intLength)

                If intLength = 5 Then
                    ProductInfo(intArray).strId = strTemp
                Else
                    Double.TryParse(strTemp, ProductInfo(intArray).dblPrice)
                End If

                ' add the line to the list box
                lstNumbers.Items.Add(ProductInfo(intArray).strId)

                intArray = intArray + 1
            Loop

            ' close the file
            inFile.Close()

            ' select the first line in the list box
            lstNumbers.SelectedIndex = 0

        End If
    End Sub
End Class


When I run this code my list box is empty and I am not sure where I went wrong. Any help would be appreciated.
 
The error is here:
Integer.TryParse(strTemp, intLength)


You try to parse a string into an integer. Because you used TryParse, you receive no exception from an invalid cast. The cast is also completely useless, since the .Length property of the String class is already explicitly an integer. Presumably it should be:
intLength = strTemp.Length


Also the algorithm as is is fairly weak, what happens if you have a 10.00 price? The string is 5 characters long and you assume it's a product code. This kind of validation suits RegEx very much:

     Private Sub frmMain_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        ' If the file exists...
        If IO.File.Exists("ItemInfo.txt") Then
            ' ... read its contents into a string array.
            Dim strLines() As String = File.ReadAllLines("ItemInfo.txt")
            ' Define our two RegEx objects with the match strings for 99AAA and 99999999.99
            Dim rgxProductCode As New RegEx("^\d{2}[a-zA-Z]{3}$")
            Dim rgxProductPrice As New RegEx("^\d+.\d{2}$")
            ' Record counter.
            Dim intArray As Integer = 0
            ' Process each record completely, two lines at a time.
            For L = 0 To UBound(strLines) Step 2
                ' Test if the product code and price are in the proper formats.
                If Not rgxProductCode.IsMatch(strLines(L)) Or Not rgxProductPrice.IsMatch(strLines(L + 1)) Then 
                    ' If not back up the line counter by one, because we only want to skip one line at a time in case there is a blank, to be able to resync.
                     L -= 1
                Else
                    ' If both string match, save the record in the ProductInfo array ...
                    ProductInfo(intArray).strId = strLines(L)
                    ProductInfo(intArray).dblPrice = System.Convert.ToDouble(strLines(L + 1))
                    ' ... add it to the list ...
                    lstNumbers.Items.Add(ProductInfo(intArray).strId)
                    ' ... and increment the record counter.
                    intArray += 1
                End If
            Next
            ' After everything is processed set the list index to 0.
            lstNumbers.SelectedIndex = 0
        End If
    End Sub
 
Last edited:
Thank you for the reply. We have not covered RegEx yet in my class so I was not comfortable using it. Instead I came up with a new algorithm for my If condition since all of the product IDs end with 3 letters.

If strTemp.ToUpper Like "??[A-Z][A-Z][A-Z]" Then


Thanks again for the help :)
 
I'm not quite sure why you need to distinguish product IDs from prices at all. Surely it's simply pairs of lines, with the first line the product ID and the second line the price. If you can count to 2 then you can read the file, e.g.
Using reader As New IO.StreamReader("file path here")
    Do Until reader.EndOfStream
        Dim productID = reader.ReadLine()
        Dim price = reader.ReadLine()

        '...
    Loop
End Using
That code assumes that the file will always be valid. If you cannot make that assumption then the logic would be a little different but you still don't need any logic other than counting to 2 to recognise what's an ID and what's a price other than whether every second value can be converted to a Decimal.
 

Latest posts

Back
Top