如何在while循环中获取多个用户输入

时间:2019-01-26 01:32:53

标签: c#

我无法在while循环中要求用户输入另一个单词。

我是一个初学者,无法看到我的错误在哪里。我在网上搜索了类似的解决方案,但无济于事。这是我所拥有的:

Console.WriteLine("Which word is the longest?");
int howMany = 5;//Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter {0} words and I will tell you which is the longest", howMany);
string userWord = Console.ReadLine();
int counter = 0;

while (counter < howMany)
{
     Console.WriteLine("Enter a word {0} > ", counter + 1);
     string wordLength = (userWord.Length).ToString();
     counter++;
}

Console.ReadLine();

2 个答案:

答案 0 :(得分:0)

无论您在此处实施哪种模式,都需要再次读取用户输入,而您并没有这样做...

while (counter < howMany)
{
     Console.WriteLine("Enter a word {0} > ", counter + 1);
     string wordLength = (userWord.Length).ToString();
     counter++;
     userWord = Console.ReadLine(); // yehaa
}

或者看起来这似乎是for循环的工作

for (int i = 0; i < howMany; i++)
{
   Console.WriteLine("Enter a word {0} > ", counter + 1);
   userWord = Console.ReadLine(); // yehaa
   wordLength = (userWord.Length).ToString();
   ...
}

注意 :我有点不清楚您的逻辑或如何实现它。但是,我认为您可以看到这里发生了什么

答案 1 :(得分:0)

您需要将readline移入循环, 您的程序正在执行,然后读取该行。

            Console.WriteLine("Which word is the longest?");
        int howMany = 5;//Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("Enter {0} words and I will tell you which is the longest", howMany);
        string LongestWord = "";
        int counter = 0;

        while (counter < howMany)
        {
            Console.WriteLine("Enter a word {0} > ", counter + 1);
            string temp = Console.ReadLine();
            if (temp.Length > LongestWord.Length) // check if the new word is longer than the current longest word
            {
                LongestWord = temp;
            }
            counter++; //update counter
        }
        Console.WriteLine($"{LongestWord} is the longest word"); // after exiting the loop, print the longest word