【发布时间】:2021-02-04 09:55:53
【问题描述】:
我无法弄清楚如何跳出包含 switch 语句的循环。 我需要按两次 0 才能退出控制台,为什么? 我该如何解决它以从第一次退出
public void Start()
{
int choice = 0;
bool trueNumber = false;
do
{
ShowMenu(); // display the menu
Console.Write("Your Choice : ");
trueNumber = int.TryParse(Console.ReadLine(), out choice);
if (!trueNumber)
Console.WriteLine("Your Choice must be an integer. Try again.");
switch (choice) // select the relevant function based on user input
{
case 1:
CalculateCelsiusToFahrenheit();
break;
case 2:
CalculateFahrenheitToCelsius();
break;
case 0:
return; // exit when i press 0
default:
Console.WriteLine("Invalid Option: Choose 0, 1, or 2 Thank you ");
break;
}
} while (choice != 0);
}
【问题讨论】:
-
仅供参考:如果提供的文本不是有效数字,
TryParse会将choice设置为 0。 -
调用
Start()的代码是什么? -
这看起来不错关于退出。如果用户输入零,它将退出。您可以将
return替换为简单的break,因为它会脱离choice == 0以来的do-while 循环。 -
“为什么我需要按两次 0 才能退出控制台?” - 您是否碰巧从 IDE(Visual Studio)启动程序。根据设置,VS 会为您添加“保持打开状态直到按下按键”。这可能是你在这里看到的吗?尝试在 Release 模式下构建并从 cmd-line 执行 .exe。
-
我刚刚运行了你的代码,它工作得很好..