C# 如何使程序返回Console.Writeline(“错误无效输入”)而不是给我一个异常?
在我的代码中:C# 如何使程序返回Console.Writeline(“错误无效输入”)而不是给我一个异常?,c#,exception,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.WriteL
{
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只需更改
int coffetype = int.Parse(Console.ReadLine());
到
你用
此方法尝试将输入字符串转换为整数,但如果出现错误,它不会引发异常,只返回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;
}
请您解释一下!就在int.tryparse之前!的用途好吗?当然@MattJones,!是布尔表达式的一个求反运算符,如果您查看tryparse签名,您将看到如果该方法可以解析提供的字符串,则返回True,否则返回false,因此在本例中,我们需要写入“错误无效输入”“只有当TryParse无法解析字符串值时,它基本上可以这样做,这样我就不必把bool=int.TryParse(输入,输出);
int coffetype;
string input = Console.ReadLine();
if(!Int32.TryParse(input, out coffetype))
Console.WriteLine(coffeType.ToString() + " IS AN INVALID INPUT");
else
{
.....
}
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;
}