0

I want the program to continue on running after a user enters an invalid input. When a user inputs a string, an error message displays and then the program closes, however I want the program to continue asking the user to enter a valid input. I tried put the try/catch inside the do/while but it doesn't seem to work for me.

        Int16 dollars;
        try
        {
            do
            {
                Console.WriteLine("Enter a value, or 0 to exit.");
                dollars = Convert.ToInt16(Console.ReadLine());
                if (dollars >= 1)
                {
                    Console.WriteLine("your current balance is");
                    myBank.addMoney(dollars);
                    myBank.getValue();
                }
                else if (dollars < 0)
                {
                    Console.WriteLine("You have entered a negative number, your current balance is");
                    myBank.getMoney(dollars);
                    myBank.getValue();
                }

            } while (dollars != 0);
        }
        catch
        {
            Console.WriteLine("The value you have entered is invalid");
            Console.ReadKey();
        }
Chetan
  • 6,711
  • 3
  • 22
  • 32
  • 3
    `"I tried put the try/catch inside the do/while"` - Not according to the code shown here you didn't. But that's exactly what you *could* do. Handle the error in the loop and continue with the logic. Or, as a more ideal alternative, take a look at `int.TryParse()` to test the input *without* throwing an exception. Rendering the problem moot. – David Nov 02 '17 at 23:44
  • Look at int.TryParse (you can use it instead of Convert.ToInt16). And please stop using Int16 type, it's mad. ;-) – Al Kepp Nov 02 '17 at 23:45
  • You need to be using `Int16.TryParse` instead of the `convert` class – S. Walker Nov 02 '17 at 23:46
  • Not here, but i did try putting the try/catch inside the do/while but when I did, the error highlights to the "dollars" in the while statement. –  Nov 02 '17 at 23:48
  • @rcbutera12: `"the error highlights to the "dollars" in the while statement"` - What error? So far you've implied that you attempted code you're not showing, and got an error you're not telling... – David Nov 02 '17 at 23:50
  • @rcbutera12 the correct thing is to have the try catch in side the loop (even tho people say 'use tryparse' you should still know how to put the correct try catch in place). Change it, then post a new question , including the code and the exact error message – pm100 Nov 02 '17 at 23:54

1 Answers1

3

Instead of converting the input, use TryParse.

Console.WriteLine("Enter a value, or 0 to exit.");
var input = Console.ReadLine();
var ok = Int16.TryParse(input, out dollars);
if (!ok)
{
    Console.WriteLine("Please input a valid number.");
    continue;
}
John Wu
  • 50,556
  • 8
  • 44
  • 80