【问题标题】:breaking out a loop in c#在c#中打破一个循环
【发布时间】: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。
  • 我刚刚运行了你的代码,它工作得很好..

标签: c# loops


【解决方案1】:

如果您从 IDE(如 Visual Studio)运行此程序,控制台应用程序的默认行为是以“按任意键继续”结束。所以它会等待显示输出。

相关回答:VS setting

【讨论】:

    猜你喜欢
    • 2011-09-06
    • 2020-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-30
    • 1970-01-01
    相关资源
    最近更新 更多