【问题标题】:Use infinite loop to restart program on any key press and to leave loop on specific key press使用无限循环在任何按键时重新启动程序并在特定按键时离开循环
【发布时间】:2017-11-07 18:13:35
【问题描述】:

我目前让用户输入温度值,并根据温度给出建议。我想设置一个循环来询问用户输入,直到用户按下“N”或“n”。

例如:

//用户输入

//临时推荐

//继续?按任意键,N 或 n 退出。

按下任何键都会再次要求用户输入,N 或 n 将导致程序感谢屏幕上的用户不再显示临时推荐。教授建议我们使用额外的方法来达到预期的效果。

当前错误代码:

Console.WriteLine("Continue? Press any key to continue, N or n to exit:\n");
{
if (Console.ReadKey().Key == ConsoleKey.N)
else if (Console.ReadKey().Key == ConsoleKey.n)
return;}
}
Console.WriteLine("Thank you");

【问题讨论】:

标签: c#


【解决方案1】:

您可以在 while 循环中使用局部变量,如下所示:

static void main(string[] args)
{
    bool keepGoing = true;

    while (keepGoing)
    {
        DoYourWork();

        Console.WriteLine("Continue? Press any key to continue, N or n to exit:");

        var userWantsToContinue = Console.ReadLine();

        keepGoing = userWantsToContinue?.ToUpper() != "N";
    }
}

【讨论】:

    【解决方案2】:

    你可以使用break退出循环

    while(true)
    {
      //process temperature conversion
      Console.Write("Continue? Press any key to continue, N or n to exit:");
      if (Console.ReadKey().Key == ConsoleKey.N)
      {
        break;
      }
    
    }
    

    【讨论】:

      【解决方案3】:

      进入do..while循环:)

      private static void DoWhatever(string data)
      {
          // process your temp
      }
      
      // inside main somewhere
      Console.WriteLine("Enter temp:");
      
      do
      {
          var temp = Console.ReadLine();
          DoWhatever(temp);
          Console.WriteLine("Continue? Press any key to continue, N or n to exit:\n");
      }while(Console.ReadKey().Key != ConsoleKey.N);
      Console.WriteLine("Thank you");
      

      【讨论】:

      • @mjwills 谢谢你,我的错;我认为 OP 的一切是理所当然的。更新了答案(实际上现在更简洁了,因为我们丢失了 2 行代码)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-31
      相关资源
      最近更新 更多