【问题标题】:Which loop do I use to ask if a user wants to continue the program in C#我使用哪个循环来询问用户是否想在 C# 中继续程序
【发布时间】:2010-03-02 23:16:31
【问题描述】:

我做了一个程序,要求输入并返回一个值。之后,我想询问用户是否要继续。但我不知道该用什么。

【问题讨论】:

    标签: c# loops


    【解决方案1】:

    您想使用do / while 循环,或带有条件break 的无限while 循环。

    【讨论】:

      【解决方案2】:

      经常使用do-while循环:

      bool @continue = false;
      do
      {
          //get value
          @continue = //ask user if they want to continue
      }while(@continue);
      

      循环将在循环条件被评估之前执行一次。

      【讨论】:

        【解决方案3】:

        这只允许 2 个键(Y 和 N):

        ConsoleKeyInfo keyInfo;
        do {
            // do you work here
            Console.WriteLine("Press Y to continue, N to abort");
        
            do {
                keyInfo = Console.ReadKey();
            } while (keyInfo.Key != ConsoleKey.N || keyInfo.Key != ConsoleKey.Y);
        } while (keyInfo.Key != ConsoleKey.N);
        

        【讨论】:

          【解决方案4】:

          我会使用do..while 循环:

          bool shouldContinue;
          do {
              // get input
              // do operation
              // ask user to continue
              if ( Console.ReadLine() == "y" ) {
                  shouldContinue = true;
              }
          } while (shouldContinue);
          

          【讨论】:

          • 这个是最容易理解的。谢谢。
          【解决方案5】:

          你可能想要一个 while 循环,比如:

          bool doMore= true;
          
          while(doMore) {
            //Do work
            //Prompt user, if they refuse, doMore=false;
          }
          

          【讨论】:

            【解决方案6】:

            使用Do While 循环。类似的东西会起作用

            int input=0;
            do
            {  
              System.Console.WriteLine(Calculate(input)); 
              input =  GetUserInput();
            } while (input != null)
            

            【讨论】:

              【解决方案7】:

              从技术上讲,任何循环都可以做到这一点,例如 for 循环(这是编写 while(true){;} 的另一种方式)

                  for (; true; )
                  {
                      //Do stuff
                      if (Console.ReadLine() == "quit")
                          {
                          break;
                      }
                      Console.WriteLine("I am doing stuff");
                  }
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2021-04-06
                • 2013-04-18
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2012-05-26
                相关资源
                最近更新 更多