如何允许用户在没有信息的情况下按回车键而不会崩溃,并使其显示不正确而不是显示错误

本文关键字:显示 崩溃 错误 不正确 用户 何允许 信息 回车 情况下 | 更新日期: 2023-09-27 18:34:22

如何允许用户按回车键并使其显示不正确而不是显示错误。在程序中,用户可以按回车键而不输入信息,系统崩溃,出现System.FormatException错误,我不知道如何解决。任何帮助将不胜感激,感谢您的阅读。

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.Parse() ,请尝试char.TryParse()

....
Console.WriteLine("Q: to quit the program");
if (!char.TryParse(Console.ReadLine(), out choice)
{
    continue; // Assuming your do/while loop will just loop. Might need to modify the while condition
}
switch (choice)
...

如果你传递垃圾数据,Parse总是会抛出。

你可以抓住它:

try
{
   choice = char.Parse(...);
}
catch (FormatException ex)
{
   //Display error
}

或者使用不会抛出的 TryParse

if (char.TryParse(..., out choice))
{
   //Value in choice
}
else
{
   //Parse Failed
}