C# 在循环时卡住

C# 在循环时卡住,c#,C#,我正在学习编码,并且一直在做一个爱好项目。我被困住了,甚至不知道如何去寻找答案。我正在尝试编写一个循环,允许我检查字符串中的空格数,如果超过2,则用户必须输入一个短语,直到满足条件为止 //Ask user for a maximum of three word phrase Console.WriteLine("Please enter a three or fewer word phrase."); s = Console.ReadLine()

我正在学习编码,并且一直在做一个爱好项目。我被困住了,甚至不知道如何去寻找答案。我正在尝试编写一个循环,允许我检查字符串中的空格数,如果超过2,则用户必须输入一个短语,直到满足条件为止

        //Ask user for a maximum of three word phrase
        Console.WriteLine("Please enter a three or fewer word phrase.");
        s = Console.ReadLine();
        int countSpaces = s.Count(char.IsWhiteSpace);
        int spaces = countSpaces;

            while (spaces > 2)
            {
                Console.WriteLine("You entered more than three words! Try again!");
                s = Console.ReadLine();
                //missing code 
            }
            Console.WriteLine("You gave the phrase: {0}", s);

        //find a way to check for more than two spaces in the string, if so have them enter another phrase until
        //condition met

在再次检查循环之前,我一直在想如何让循环返回并阅读第3行和第4行。

while循环的基本原理是在满足条件时循环。因此,您的while循环应该有希望做一些会影响该条件的事情。否则,您可能会永远循环

在本例中,您希望在
spaces>2
时循环。这意味着您最好在while循环中更新
空格

while (spaces > 2)
{
    Console.WriteLine("You entered more than three words! Try again!");
    s = Console.ReadLine();
    spaces = s.Count(char.IsWhiteSpace);
}

您必须添加代码,以满足while循环的条件,否则将得到无限循环:

while (spaces > 2)
        {
            Console.WriteLine("You entered more than three words! Try again!");
            s = Console.ReadLine();
            countSpaces = s.Count(char.IsWhiteSpace);
            spaces = countSpaces;

        }

其中一种方法是将读数移动到以下状态:


无论如何,这种计算单词的方法是错误的,因为单词可以被多个空格分隔。

循环中,你必须再次计算空格的数量。此外,您不需要
int spaces=countSpaces。您可以在
while
语句中重复使用
countSpaces
。最简单的方法是丢弃
countSpaces
spaces
变量,并更改while,如下所示:
while(s.Count(char.IsWhiteSpace)>2)
“while循环的基本原理是循环,直到满足条件为止”应为“while循环的基本原理是循环直到一个条件不再满足”或“while循环的基本原理是在一个条件满足时循环”啊,老兄。我觉得自己太傻了!!如此明显的解决方案就在眼前。非常感谢你的帮助!
using System;
using System.Linq;

public class Test
{
    public static void Main()
    {
        Console.WriteLine("Please enter a three or fewer word phrase.");

        string s; 

        while ((s = Console.ReadLine()).Count(char.IsWhiteSpace) > 2)
            Console.WriteLine("You entered more than three words! Try again!");

        Console.WriteLine("You gave the phrase: {0}", s);
    }
}