In C #, I am trying to enter a user number. Then I want to check that
- They entered a string that can be converted to double and
- They entered a value greater than zero
The method I originally created was
string inValue; double outcome; Console.WriteLine("Enter amount: "); inValue = Console.ReadLine(); while (double.TryParse(inValue, out outcome) == false) { Console.WriteLine("Initial value must be of the type double"); Console.WriteLine("\nPlease enter the number again: "); inValue = Console.ReadLine(); } outcome = double.Parse(inValue); while (outcome < 0) { Console.WriteLine("Initial value must be of at least a value of zero"); Console.WriteLine("\nPlease enter the number again: "); inValue = Console.ReadLine(); outcome = double.Parse(inValue); } return outcome;
The problem was that if the user enters the word "-10" and then "f", an exception will occur. This is because the program will go past the first check (which checks double) for the value -10, but then when βfβ is entered, it throws an exception if the second test is given.
I believe that the solution is to create a while statement that writes an error statement when either the value cannot be converted to double, or the value is converted to double and is below zero. What I donβt know how to do is convert the value to double and then evaluate to more than zero in the while statement.
source share