【问题标题】:why while loop is printing only the first element in C#? [closed]为什么while循环只打印C#中的第一个元素? [关闭]
【发布时间】:2017-04-11 06:15:20
【问题描述】:

使用系统;

namespace Loop
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] Numbers = new int[3];

            Numbers[0] = 101;
            Numbers[1] = 102;
            Numbers[2] = 103;

            int i = 0;
            while (i < Numbers.Length)
            {
                Console.WriteLine("Numbers are: "+ Numbers[i]);
                i++;
                Console.ReadKey();
            }
        }
    }
}

enter image description here

【问题讨论】:

  • Console.ReadKey(); - 只需按下它
  • 这里等待用户输入 Console.ReadKey();
  • 在它打印了 101 之后你按下了一个键吗?它对我来说很好......
  • Console.ReadKey() 放在while 循环之后。简单的调试会告诉你,当你点击这个语句时,控制台会弹出,因为它需要你的键输入。

标签: c# loops while-loop


【解决方案1】:

删除

Console.ReadKey();

否则它将等待用户输入

【讨论】:

    【解决方案2】:
    namespace Loop
    {
        class Program
        {
            static void Main(string[] args)
            {
                int[] Numbers = new int[3];
    
                Numbers[0] = 101;
                Numbers[1] = 102;
                Numbers[2] = 103;
    
                int i = 0;
                while (i < Numbers.Length)
                {
                    Console.WriteLine("Numbers are: "+ Numbers[i]);
                    i++;
    
                }
               Console.ReadKey();
            }
        }
    }
    

    如果你想等待并读取控制台Console.ReadKey();必须在while循环之外

    【讨论】:

      【解决方案3】:

      请删除

      Console.ReadKey();
      

      因为Readkey() 方法正在等待输入。如果你调试你的程序,你会意识到这是错误的吗

      【讨论】:

      • 没有必要尝试@通知提问者。当有人写了 answer 时,他们会自动收到通知,这就是您所做的。
      • 感谢@Damien_The_Unbeliever
      【解决方案4】:

      我得到了解决方案。 Console.ReadKey();这应该是在循环之外。

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-13
      • 2017-09-18
      • 2023-01-17
      • 2021-12-16
      • 2011-05-03
      • 2023-03-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多