C# 如何允许用户在无格式的情况下按enter键而不崩溃,以及如何让它显示错误而不是显示错误
如何允许用户按enter键并使其显示不正确而不是显示错误。 在程序中,用户可以按enter键而不输入信息,系统崩溃,出现system.FormatException错误,我不知道如何修复该错误。 任何帮助都将不胜感激,感谢您的阅读C# 如何允许用户在无格式的情况下按enter键而不崩溃,以及如何让它显示错误而不是显示错误,c#,menu,return,enter,C#,Menu,Return,Enter,如何允许用户按enter键并使其显示不正确而不是显示错误。 在程序中,用户可以按enter键而不输入信息,系统崩溃,出现system.FormatException错误,我不知道如何修复该错误。 任何帮助都将不胜感激,感谢您的阅读 double price, discount, answer, disprice, fahr, celc, celc2, fahr2; char test, choice; double Merc, mars, nept, uran,
double price, discount, answer, disprice, fahr, celc, celc2, fahr2;
char test, choice;
double Merc, mars, nept, uran, jup, sat, pluto, moon, venus;
do
{
Console.WriteLine("Choose from the following:");
Console.WriteLine("A: Mecury ");
Console.WriteLine("B: Venus ");
Console.WriteLine("C: Mars ");
Console.WriteLine("D: Jupitar");
Console.WriteLine("E: Saturn ");
Console.WriteLine("F: Uranus ");
Console.WriteLine("G: Neptune ");
Console.WriteLine("H: Pluto ");
Console.WriteLine("I: Moon ");
Console.WriteLine("Z: Help ");
Console.WriteLine("Q: to quit the program");
choice = char.Parse(Console.ReadLine());
switch (choice)
请尝试char.TryParse,而不是使用char.Parse:
如果传递垃圾数据,解析将始终抛出
你可以抓住它:
try
{
choice = char.Parse(...);
}
catch (FormatException ex)
{
//Display error
}
或者使用不抛出的:
if (char.TryParse(..., out choice))
{
//Value in choice
}
else
{
//Parse Failed
}
如果您显示在中调用此代码的方法| |事件,也会有所帮助。。。
if (char.TryParse(..., out choice))
{
//Value in choice
}
else
{
//Parse Failed
}