坚持while循环

时间:2016-04-01 17:44:04

标签: c#

我正在学习编码,而且我一直在做爱好计划。我陷入困境,无法弄清楚如何搜索答案。我正在尝试编写一个循环,允许我检查字符串中的空格数量,如果它超过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行。

3 个答案:

答案 0 :(得分:4)

while循环的基础是在满足条件时循环。因此,你的while循环应该会做一些会影响这种情况的事情。如果没有,你可能会永远地循环。

在您的情况下,您希望在spaces > 2时循环播放。这意味着您最好在while循环中更新spaces

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

答案 1 :(得分:0)

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

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

        }

答案 2 :(得分:0)

其中一种方法是将阅读变为条件:

http://ideone.com/vzXY7x

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);
    }
}

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