Invalid listing during input
I'm doing basic homework that 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 click "cancel" on the input field. Then I input the string "" and I get the following error:
System.InvalidCastException {"Conversion from string ""
to type 'Double' is not valid."}
I think I understand the error, I am trying to convert using CDbl to a non-numeric value. My question is, what would be the more correct way to write this code? Is this code or just a lack of error handling?
Try using Double.TryParse
Dim value as Double = Nothing
If Double.TryParse(InputBox("Enter numbers..."), value) Then
values = values + value
End If
My syntax might be off a bit, but you should get the idea
You can try using Double.TryParse or using a try catch block with Double.Parse. Since this is homework, I'll let you look at them on MSDN.
You will also get an error if they enter anything other than a double, or a value that is too large to be stored in a double.
The suggestions above should be sufficient, although you essentially want to validate user input before trying to use it.