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

  1. they have entered string can converted double and
  2. 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

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

java - Digest auth with Spring Security using javaconfig -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -