C#如何让程序在输入无效后继续运行

时间:2017-11-02 23:42:17

标签: c# exception-handling try-catch converter tryparse

我希望程序在用户输入无效输入后继续运行。当用户输入字符串时,会显示错误消息,然后程序关闭,但我希望程序继续要求用户输入有效输入。我尝试将try / catch放在do / while中,但它似乎对我没用。

        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();
        }

1 个答案:

答案 0 :(得分:3)

使用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;
}