如何让程序返回Console.Writeline(“ERROR INVALID INPUT”)而不是给我一个例外?

时间:2014-12-27 17:28:17

标签: c# exception

在我的代码中:

{
    int coffecost = 0;
    string coffesize = null;
    Console.WriteLine("1. Small 2. Medium 3. Large");
    Console.WriteLine("Choose your coffe please but enter your name first!");
    string name = Console.ReadLine();
    Console.WriteLine("So your name is {0}! What coffe would you like?", name);
    int coffetype = int.Parse(Console.ReadLine());

    switch (coffetype)
    {
        case 1:
            coffecost += 1;
            coffesize = "small";
            break;
        case 2:
            coffecost += 2;
            coffesize = "medium";
            break;
        case 3:
            coffecost += 3;
            coffesize = "Large";
            break;
        default:
            Console.WriteLine("{0} is an invalid choice please choose from one of the 3!", coffetype); 
            break;
    }

    Console.WriteLine("Receipt: \n Name: {0} \n Coffee type: {1} \n Coffee cost: {2} \n Coffee size: {3}", name, coffetype, coffecost, coffesize);
}

这个简单的程序根据咖啡的类型生成收据。现在在我的程序中,你输入1,2或3表示小,中,大。但是,如果您输入一个无效字符说“,”,那么您将收到一个异常,程序将崩溃。我希望程序返回“这不是一种咖啡!”而不是崩溃我怎么能这样做。另外,为了练习,我计划添加一个功能,您可以添加奶油,糖或人造甜味剂等成分。现在我希望能够将所有这些成分放在同一条线上并让它读出来。例如,我放入奶油,糖,人造甜味剂,它说你放入(它读出成分)但如果我不说糖,我想要它只是打印“你选择了奶油和人造甜味剂!所有感谢帮助:D

2 个答案:

答案 0 :(得分:1)

只需更改

即可
int coffetype = int.Parse(Console.ReadLine());

int coffetype = 0;

if (!int.TryParse(Console.ReadLine(), out coffetype)) {
    Console.Writeline(“ERROR INVALID INPUT”);
    return;
}

答案 1 :(得分:0)

您使用Int32.TryParse

int coffetype;
string input  = Console.ReadLine();
if(!Int32.TryParse(input, out coffetype))
   Console.WriteLine(coffeType.ToString() + " IS AN INVALID INPUT");
else
{
   .....
}

此方法尝试将输入字符串转换为整数,但是,如果出现错误,它不会抛出异常,只返回false,将变量coffetype保留为其默认值0。

在您的上下文中,您还可以避免测试,并让交换机中的默认情况处理无效输入。

int coffetype;
string input  = Console.ReadLine();

// Not really need to test if Int32.TryParse return false,
// The default case in the following switch will handle the
// default value for coffetype (that's zero)
Int32.TryParse(input, out coffetype);
switch (coffetype)
{
    case 1:
       .....
    default:
       Console.WriteLine("{0} is an invalid choice please choose from one of the 3!", coffetype);
       break;
}