Tim The Learner
Tim The Learner

Reputation: 75

How to Loop until a variable inputted by the user is an integer in VB.NET?

Here is the code I have so far:

Module Module1

    Sub Main()
        Dim A, B, C, D As Integer
        Do
            Try
                System.Console.WriteLine("How high is the cube?")
                A = Int32.Parse(Console.ReadLine())
            Catch leg As System.FormatException
                System.Console.WriteLine(leg.Message)
            Finally
            End Try
        Loop Until A =
        System.Console.WriteLine("How wide is the cube?")
        B = Int32.Parse(Console.ReadLine())
        System.Console.WriteLine("How long is the cube?")
        C = Int32.Parse(Console.ReadLine())
        D = A * B * C
        Console.WriteLine(D)
        System.Console.ReadKey()
    End Sub

End Module

I want the first try block to loop till A is an Integer in case the user inputs a letter instead of a number. Does anyone know how I might do that?

Upvotes: 2

Views: 2133

Answers (4)

I have one more concept to add. Methods fire exceptions, to let you handle inlikely problems and prevent application crash. Readlin and writeline can throw exceptions, and if you dont catch them and they happen, your program will crash. Use the try block to do what its meant for: handle unlikely crashes to increae robustness. To do a thorough job you should research the exceptions and write code to prevent the crash.

Upvotes: 0

KevenDenen
KevenDenen

Reputation: 1726

Here's a real world example to further expand on one reason why using Try/Catch to control program flow is bad. At least in .NET, throwing an error and handling it in a catch takes a lot more execution time than properly handling the error using proper control flow structures.

I picked up a project from a coworker who was using a function to clean input coming in that was supposed to be numeric. He was using something like the following code to do it.

Public Shared Function SafeDouble(value As Object, Optional DefaultValue As Double = 0.0) As Double
    Dim CleanDouble As Double

    Try
        CleanDouble = CDbl(value) 'try to convert to a double
    Catch ex As Exception
        CleanDouble = DefaultValue 'if it fails use the default value
    End Try

    Return CleanDouble
End Function

Which worked fine for the one place he was using it originally to process one row of data. The problem came about when I started using this to process 1000s of rows of data. The execution bogged down big time when it hit this section of the import.

Using some timers, I determined that it was taking between 50 and 100 milliseconds for each value that it couldn't convert and threw an exception for.

I changed the code to use a proper control structure and the time dropped to 2 to 5 milliseconds per value it couldn't convert. The current code is below. I know that it's possible that some value might come in that isn't numeric. If it isn't numeric, I just assign the default value right away.

Public Shared Function SafeDouble(value As Object, Optional DefaultValue As Double = 0.0) As Double
        Dim CleanDouble As Double

        Try
            If IsNumeric(value) Then 'test to see if the data is numeric before converting it
                CleanDouble = CDbl(value)
            Else
                CleanDouble = DefaultValue 'if it isn't numeric, use default value
            End If
        Catch ex As Exception
            CleanDouble = DefaultValue 'if something unexpected happens, use default value
        End Try

        Return CleanDouble
    End Function

As you can see, I have handled the expected error of it not converting because it isn't numeric. This should account for the majority of issues that are likely to occur. I still leave the try/catch in there in case some other, unexpected error occurs.

Upvotes: 0

Dai
Dai

Reputation: 155250

In C# (conversion to VB is an exercise for the reader):

public static Int32 GetInt32() {

    Int32 value;
    while( !Int32.TryParse( Console.ReadLine(), out value ) ) {
        Console.WriteLine("Please enter an integer");
    }
    Console.WriteLine("You entered {0}", value);
    return value;
}

Upvotes: 0

pinkfloydx33
pinkfloydx33

Reputation: 12749

Use TryParse instead of your try/catch block in conjunction with a do loop. It returns True when it succeeds and puts the int32 value into the variable a.

            Dim a As Integer, tmp As String

            Do
                System.Console.WriteLine("How high is the cube?")
                tmp = Console.ReadLine()
            Loop While Int32.TryParse(tmp, a) = False

After the loop, the value stored in a will be an integer. Repeat this for each of the other values.

You can also do like Dai does in his C# sample, and not bother storing into a temporary variable:

        Dim a As Integer

        Do
            System.Console.WriteLine("How high is the cube?")
        Loop While Int32.TryParse(Console.ReadLine(), a) = False

If you MUST do it with Try/Catch for an assignment, you can try this though for practical purposes I would do it as above.

        Dim a As Integer, valid As Boolean = True
        Do
            Try
                System.Console.WriteLine("How high is the cube?")
                a = Int32.Parse(Console.ReadLine())
            Catch ex As Exception
                valid = False
            End Try
        Loop While Not valid

Upvotes: 3

Related Questions