c# - Test to ensure the user input is a double and is greater than zero? -
in c# trying have user input number. want check that
- they have entered string can converted double and
- they have entered value greater zero
the method have created
string invalue; double outcome; console.writeline("enter amount: "); invalue = console.readline(); while (double.tryparse(invalue, out outcome) == false) { console.writeline("initial value must of type double"); console.writeline("\nplease enter number again: "); invalue = console.readline(); } outcome = double.parse(invalue); while (outcome < 0) { console.writeline("initial value must of @ least value of zero"); console.writeline("\nplease enter number again: "); invalue = console.readline(); outcome = double.parse(invalue); } return outcome;
the problem if user entered "-10" , "f" exception occur. because program move past first check (that checks double) value of -10 when "f" entered throws exception when given second test.
i believe solution create while statement writes error statement when either value cannot converted double or value converted double , below zero. don't know how have value converted double , evaluated being greater 0 in while statement.
you're on right track - need have single while loop gets input , tries both validations. 1 way create boolean value tracks whether or not value valid, , use condition loop:
double outcome = 0; bool valid = false; while (!valid) { console.writeline("enter amount: "); string invalue = console.readline(); if (double.tryparse(invalue, out outcome) == false) { console.writeline("initial value must of type double"); console.writeline("\nplease enter number again: "); } else if (outcome < 0) { console.writeline("initial value must of @ least value of zero"); console.writeline("\nplease enter number again: "); } else { valid = true; } } return outcome;
it's possible put both conditions in while statement, approach lets provide different message depending on conditions failed.
Comments
Post a Comment