.net - How can I check VB, console application, user input to make sure they entered a valid number? -



.net - How can I check VB, console application, user input to make sure they entered a valid number? -

vb not language of selection , have school , i'm not having easy time vb's documentation. i'm creating simple console application accepts user input: degrees in celsius, , converts fahrenheit. want create sure if user hits come in without entering degrees in celsius, if else statement grab , write come in celsius again. here's i've tried:

module module1 'chapter 2: celcius fahrenheit 'programmer: scott mcpherson 'date: feb 2, 2012 'purpose: convert user input celcius output fahrenheit ' 'declaration dim deccelcius decimal = 0 dim decfahrenheit decimal = 0 sub main() 'input in celcius console.write("enter degrees in celsius: ") console.writeline() if cdec(console.readline()) <> 0 deccelcius = cdec(console.readline()) decfahrenheit = 1.8 * deccelcius + 32 else console.writeline("don't create me inquire again! come in degrees in celsius: ") deccelcius = cdec(console.readline()) decfahrenheit = 1.8 * deccelcius + 32 end if console.writeline() console.writeline("degrees in fahrenheit = " & decfahrenheit) console.read() end sub end module

how can work?

the biggest problem current method of validating input cdec operator doesn't homecoming error when conversion fails. you're compensating checking see if entered value converted 0, means you're going display rude error message if come in 0, valid temperature value!

so rather cdec operator, want switch using decimal.tryparse method, has advantage of separating success/failure actual converted value.

the simple overload of method accepts 2 parameters: string value want convert (in case, returned console.readline() method) , reference (in vb.net terms, value passed byref) variable of type decimal filled in result of conversion, if successful. function returns boolean value indicates success or failure.

you away using simple overload, it's "better" utilize somewhat more complicated version because allows specify civilization utilize when attempting parse specified value. since cultures utilize periods (.) decimal separator, , others utilize comma (,), necessary culture-neutral application. might bit forward-looking in case, though. :-)

beyond fixing immediate problem, improve replace if/else if statements while loop. way, maintain running on , on until user manages come in valid number. not gives user many chances need, saves having duplicate code within both of if blocks.

.net vb.net decimal type-conversion

Comments

Popular posts from this blog

How do I check if an insert was successful with MySQLdb in Python? -

delphi - blogger via idHTTP : error 400 bad request -

postgresql - ERROR: operator is not unique: unknown + unknown -