Reputation: 117
I'm learning to code and I've been working on a hobby program. I'm stuck and unable to figure out how to even search for the answer. I'm trying to write a loop that will allow me to check the number of white spaces in a string and if it exceeds 2, then the user must enter a phrase until the condition is met.
//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
I'm stuck on how to get the loop to go back and read lines 3 and 4 before checking the loop again.
Upvotes: 2
Views: 792
Reputation: 21400
One of the ways to do it is to move reading into condition:
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);
}
}
Anyway, such way of counting words is wrong as words can be separated by more then one space.
Upvotes: 0
Reputation: 1
You have to add code so the condition on the while loop can be satisfied or else you will get an infinite loop:
while (spaces > 2)
{
Console.WriteLine("You entered more than three words! Try again!");
s = Console.ReadLine();
countSpaces = s.Count(char.IsWhiteSpace);
spaces = countSpaces;
}
Upvotes: 0
Reputation: 25370
The basics of a while loop is to loop while a condition is met. Therefore, your while loop should hopefully be doing something that will affect that condition. If not, you'll probably loop forever.
In your case, you want to loop while spaces > 2
. That means you've better be updating spaces
inside your while loop:
while (spaces > 2)
{
Console.WriteLine("You entered more than three words! Try again!");
s = Console.ReadLine();
spaces = s.Count(char.IsWhiteSpace);
}
Upvotes: 4