2

This is the code I have. It works and sends an error to the user when they input something other than a number. What I need to figure out is how to send the same error if they try to enter a string again.

Console.WriteLine("Type in a number and then press enter:");
try
{
    num2 = Convert.ToDouble(Console.ReadLine());
}
catch
{
    Console.WriteLine("Please Enter a valid numerical value!");
    Console.WriteLine("Please enter a valid number and then press enter:");
    num2 = double.Parse(Console.ReadLine());
}
Spirit
  • 631
  • 7
  • 11

4 Answers4

5
double result;
do
{
    Console.Write("Type in a number and then press enter: ");
}
while (!double.TryParse(Console.ReadLine(), out result));
Console.WriteLine($"Thanks! {result}");
Matthew Whited
  • 22,160
  • 4
  • 52
  • 69
3

You should use double.TryParse, which returns a bool indicating whether or not the parsing was successful, and which sets an out parameter to the converted value. Then you can do something like this:

Console.WriteLine("Type in a number and then press enter:");

double userInput;

while (!double.TryParse(Console.ReadLine(), out userInput)
{
    Console.WriteLine("Please Enter a valid numerical value!");
    Console.WriteLine("Please enter a valid number and then press enter:");
}

// After the above loop, the variable 'userInput' will contain the user's number

This is more intentional than using try/catch to do input validation. For more reading, see: Why are Exceptions said to be so bad for Input Validation?

Rufus L
  • 36,127
  • 5
  • 30
  • 43
  • To be fair having a try/catch is not "expensive". throwing an exception especially one that is deeply nested is "expensive". (Though either way when based on user input the overhead of the exception stack rollback is less than the expense on waiting for a user to a button.) – Matthew Whited Jul 26 '19 at 21:13
2

Create a boolean verifiedNumber then create a while loop

while(!verifiedNumber) {
   Console.WriteLine("Type in a number and then press enter:");
   try { 
      num2 = Convert.ToDouble(Console.ReadLine()); 
      verifiedNumber = true;
   } 
   catch { 
      Console.WriteLine("Please Enter a valid numerical value!"); 
   }
}
William V.
  • 343
  • 1
  • 13
0

As another althernative you can use for loop:

double result;

for(; ; )
{
    Console.WriteLine("Type in a number and then press enter:");

    if(!double.TryParse(Console.ReadLine(), out result)){
        Console.WriteLine("Please Enter a valid numerical value!");
        Console.WriteLine("Please enter a valid number and then press enter:");
    }
    else
    {
        break;
    }
}
Console.WriteLine($"Result = {result}");
GoldenAge
  • 2,918
  • 5
  • 25
  • 63