0

I would like to know how to edit the following code to make users enter a number if they enter a string for any of the following prompts.

        Console.Write("\nPlease enter a number: ");
        double num1 = Convert.ToDouble(Console.ReadLine());

        Console.WriteLine("\nPlease enter a operator:  ");
        string optr = Console.ReadLine();

        Console.Write("Please enter a number: ");
        double num2 = Convert.ToDouble(Console.ReadLine());

        double total;
        string end;
            do
            {      

                switch (optr)
                {
                    case "+":
                        total = (num1 + num2);
                        Console.Write("Total : " + total);
                        break;
                        Console.Write("Invalid operator");
                        break;
                }

                Console.WriteLine("\n \nDo you want to make another calculation? Yes or No: ");
                end = Console.ReadLine();

            } while (end != "No");

            Console.Write("Press Enter key to exit");
            Console.ReadKey();
  • 2
    Does this answer your question? [How can I check if a string is a number?](https://stackoverflow.com/questions/6733652/how-can-i-check-if-a-string-is-a-number) – Timothy G. May 07 '21 at 02:38
  • As a rule of thumb, exceptions should be used for unexpected or exceptional events, like failing to write to disk. Having the user enter something incorrectly is probably an expected event, so it is better to check that the operation is valid before attempting it, i.e. see `Double.TryParse` – JonasH May 07 '21 at 07:45

1 Answers1

0

Rather than handling the exception, I would store the Console.ReadLine() in a string for both of the numbers, then test to see if they convert to a Double. If they do, move on, if they don't, show an error and ask the user to try again.

Double.TryParse will allow you to attempt to convert from String to Double and will never throw an exception.

https://learn.microsoft.com/en-us/dotnet/api/system.double.tryparse?view=net-5.0#System_Double_TryParse_System_String_System_Double__

Will Walsh
  • 1,799
  • 1
  • 6
  • 15