Can someone please help fix the coding issue for the application "Apartment Rental by City?" (Exception Unhandled - "Input string was not in correct format")

Laura 1 Reputation point
2020-12-17T16:12:07.66+00:00
Option Strict On  

49206-exception-unhandled.png
Public Class frmApartment
' Class level private variables
Public Shared _intSizeOfArray As Integer = 9
Public Shared _strDisplayCity(_intSizeOfArray) As String
Private _strCityId(_intSizeOfArray) As String
Private _decInitialPrice(_intSizeOfArray) As Decimal
Private _intQuantity(_intSizeOfArray) As Integer

    Private Sub frmApartment_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load  
        ' The frmApartment load event reads the rental text file and fills the  
        ' Listbox object with the rental items.  
  
        ' Intialize an instance of the StreamReader object and declare variables.  
        Dim objReader As IO.StreamReader  
        Dim strLocationAndNameOfFile As String = "c:\rentals.txt"  
        Dim intCount As Integer = 0  
        Dim intFill As Integer  
        Dim strFileError As String = "The file is not available. Restart when the file is available."  
  
        ' Verify the file exists  
        If IO.File.Exists(strLocationAndNameOfFile) Then  
            objReader = IO.File.OpenText(strLocationAndNameOfFile)  
            ' Read the file line by line until the file is completed  
            Do While objReader.Peek <> -1  
                _strDisplayCity(intCount) = objReader.ReadLine()  
                _strCityId(intCount) = objReader.ReadLine()  
                _decInitialPrice(intCount) = Convert.ToDecimal(objReader.ReadLine())  
                _intQuantity(intCount) = Convert.ToInt32(objReader.ReadLine())  
                intCount += 1  
            Loop  
            objReader.Close()  
  
            ' The ListBox object is filled with the City IDs  
            For intFill = 0 To (_strCityId.Length - 1)  
                lstCityId.Items.Add(_strCityId(intFill))  
            Next  
        Else  
            MsgBox(strFileError, , "Error")  
            Close()  
        End If  
    End Sub  
  
    Private Sub btnCalculate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalculate.Click  
        ' The btnCalculate click  event calculates the average apartment rental within the 10 cities.  
        ' Declare variables  
        Dim intSelectedCity As Integer  
        Dim strMissingSelection As String = "Missing Selection"  
        Dim strSelectCityError As String = "Select a City"  
  
        ' If the ListBox object is selected, call the calculate procedure  
        If lstCityId.SelectedIndex >= 0 Then  
            intSelectedCity = lstCityId.SelectedIndex  
        Else  
            MsgBox(strSelectCityError, , strMissingSelection)  
        End If  
    End Sub  
  
    Private Sub MakeObjectsVisible()  
        ' This procedure MakeObjectsVisible is called to display the Form objects  
        lblAverageCost.Visible = True  
        lblSelectCity.Visible = True  
        lblMedianCost.Visible = True  
        lstCityId.Visible = True  
    End Sub  
  
    Private Sub mnuDisplay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuDisplay.Click  
        ' The mnuDisplay click event creates an instance of the frmDisplayCity  
        Dim frmSecond As New frmDisplayCity  
  
        ' Hide this form and show the Display City form  
        Hide()  
        frmSecond.ShowDialog()  
    End Sub  
  
    Private Sub mnuClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuClear.Click  
        ' The mnuClear click event clears and resets the form  
        lblSelectCity.Visible = False  
        lblMedianCost.Visible = False  
        lblAverageCost.Visible = False  
    End Sub  
  
    Private Sub mnuExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuExit.Click  
        ' The mnuExit click event closes the application  
        Application.Exit()  
    End Sub  
End Class  

' The frmDisplayCity class is opened by frmApartment
' and displays the inventory file in sorted order

Option Strict On

Public Class frmDisplayCity
Private Shared _DisplayCity As Array
Private Shared _strDisplayCity As IEnumerable(Of Object)

Private Sub frmDisplayCity_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load  
    ' The frmDisplayCity load event is a second form that   
    ' displays the sorted cities and their rental costs  

    Dim strCity As String  

    ' Sorts the _strDisplayCity array  
    Array.Sort(frmDisplayCity._DisplayCity)  

    ' Displays the _strDisplaycity array  
    For Each strCity In frmDisplayCity._strDisplayCity  
        lstCityDisplay.Items.Add(strCity)  
    Next  
End Sub  

Private Sub btnReturn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReturn.Click  
    ' This Sub procedure opens the first form  
    Dim frmFirst As New frmApartment  

    Hide()  
    frmFirst.ShowDialog()  
End Sub  

End Class

49234-capture.jpgnhandled.png

49235-capture-2.jpg49216-capture-3.jpg

Visual Studio
Visual Studio
A family of Microsoft suites of integrated development tools for building applications for Windows, the web and mobile devices.
4,634 questions
VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,580 questions
Visual Studio Debugging
Visual Studio Debugging
Visual Studio: A family of Microsoft suites of integrated development tools for building applications for Windows, the web and mobile devices.Debugging: The act or process of detecting, locating, and correcting logical or syntactical errors in a program or malfunctions in hardware. In hardware contexts, the term troubleshoot is the term more frequently used, especially if the problem is major.
943 questions
{count} votes

5 answers

Sort by: Most helpful
  1. Anonymous
    2020-12-17T16:49:42.467+00:00

    Hi

    One way to approach the problem.

    On the line BEFORE you line (line 19 in your image), put the following code. At the point where the exception is occurring then you will get a MessageBox showing the current value as read by your ObjectReader.

            Try
                obj = objReader.ReadLine()
                Dim dec As Decimal = Convert.ToDecimal(obj)
            Catch ex As FormatException
                MessageBox.Show(obj.ToString)
                Stop
            End Try
    

    I suspect you will find it to be something that doesn't form a valid Decimal - such as a String of alpha character(s).

    You can prevent a 'crash' by using a function (such as the following) which will return a value of ZERO instead of an exception. This doesn't solve the issue where your data is returning an unexpected value though.

        Function GetDecimal(s As String) As Decimal
            Dim v As Decimal = 0.0D
            If Decimal.TryParse(s, v) Then Return v
            Return 0.0D
        End Function
    

    Instead of above code, you would try:

            Dim dec As Decimal = 0.0D
            Try
                obj = objReader.ReadLine()
                dec = GetDecimal(obj.ToString)
            Catch ex As FormatException
                MessageBox.Show(obj.ToString)
                Stop
            End Try
            MessageBox.Show(obj.ToString & "  " & dec.ToString)
            Stop
    
    0 comments No comments

  2. Viorel 112.5K Reputation points
    2020-12-17T16:54:30.503+00:00

    It seems that the rentals.txt file, mentioned in your task and code, is not processed correctly or is invalid. The third line of group is expected to be a decimal number.

    Show some details about this file.

    You can also keep the results of ReadLine into some variables for easier debugging.

    0 comments No comments

  3. Laura 1 Reputation point
    2020-12-17T20:24:23.04+00:00

    This is the format of the rentals.txt file49323-rentals.jpg


  4. WayneAKing 4,921 Reputation points
    2020-12-17T20:30:23.14+00:00

    You appear to be working on the same assignment that another poster was
    working on in the MSDN Visual Basic forum three years ago. After getting the
    OP to post the project including the data file where it could be retrieved,
    I discovered that the data file being used - rentals.txt - had an irregular
    combination of CR and LF characters. Specifically it had:

    (1) 0x0A characters only for end-of-line. This is typical of a file that
    has been created on a Unix/Linux system.

    (2) It had extra 0x0A characters at the end of the file: 0x0A 0x0A 0x0A
    This indicates additional blank lines at the end of the file that should
    not be there.

    The OP had downloaded the text file from the project site, which explained
    it's odd format. I suggested the OP recreate the file manually - using
    WordPad preferably so as to better see where line breaks are occurring and
    to be able to "see" the blank lines. After doing that the OP's original
    problem disappeared.

    Windows uses CRLF pairs to indicate EOL rather than just a solitary LF.
    Some software can handle these different combinations automatically, others
    require conversion.

    The presence of extra blank lines at the end of the file caused the OP's
    program to read those lines and try to process them as if they contained
    data. This would cause a string format exception to be thrown.

    You should try opening the data file in WordPad, and scroll to the bottom.
    If it appears to have blank lines at the bottom, backspace to remove them
    and save the file. Then try your program again. Note that this suggestion
    is just to address one possible cause of the format exceptions. There
    may well be other issues to address.

    • Wayne
    0 comments No comments

  5. Viorel 112.5K Reputation points
    2020-12-17T20:40:55.16+00:00

    The rentals****.txt file seems to contain median apartment rental costs in the ten most expensive cities, i.e. pairs of city names and costs.

    However, your code that executes four ReadLine in a loop does not seem suitable for such file. Or maybe you can change it to:

    Do While objReader.Peek <> -1
       _strDisplayCity(intCount) = objReader.ReadLine()
       _strCityId(intCount) = intCount.ToString();
       _decInitialPrice(intCount) = Convert.ToDecimal(objReader.ReadLine())
       _intQuantity(intCount) = 0
       intCount += 1
    Loop
    

    It is not clear how to get _strCityId and _intQuantity from rentals****.txt file.