views:

94

answers:

4

I'm doing a basic homework assignment which looks like this:

    While input <> -1
        input = CDbl(InputBox("Enter numbers to add, enter -1 to stop"))
        values = values + input
    End While

It works fine until I press 'cancel' on the input box. Then the string input is "", and I get the following error:

System.InvalidCastException {"Conversion from string "" to type 'Double' is not valid."}

I think I understand the error, I'm trying to convert using CDbl a non-numeric value. My question is what would be a more proper way to write this code? Is it the code, or just a lack of error handling?

Thanks

Aaron

A: 

You could try using Double.TryParse or using a try catch block with Double.Parse. Since it's a homework assignment, I'll let you look them up on MSDN.

Jason Down
A: 

Try using Double.TryParse

Dim value as Double = Nothing
If Double.TryParse(InputBox("Enter numbers..."), value) Then
    values = values + value
End If

My syntax may be a bit off, but you should get the idea

Bob
A: 

You'd also get an error if they entered anything other than a double or a value too big to be stored in a double.

The suggestions made should be enough though, you essentially want to validate the user input before you attempt to cast it.

Robert
A: 

Thanks, the TryParse worked exactly the way you described it.

Aaron