Reputation:
I'm trying to get some practise on C# ready for my time constrained test in 2 weeks time, and have been trying to complete exercises I've found in books & on the internet.
The exercise asked to use a while loop to ask a user to enter their name, and if it was not "XXX" then it can continue to loop. But the problem I've got is, after writing the loop, it just continues, there is no way the user can enter "XXX" to stop the program, so I was wondering if anyone knew the solution to this?
Here is the code i've wrote so far..
String sName;
//Declaring the variable
Console.Write("Enter a name (or XXX to end): ");
sName = Console.ReadLine();
//Prompting user to enter the name or to end the program by telling them to type XXX
while (sName != "XXX")
{
Console.Write("The Name is: " + sName);
Console.WriteLine();
}
//Start loop
Console.WriteLine("You are now past the while loop");
//If XXX is typed, message is displayed
Console.WriteLine("Press any key to close");
Console.ReadKey();
//Prevent program from closing
Upvotes: 0
Views: 229
Reputation: 26209
you are not prompting the user for next input. Add following statement in your while loop
sName = Console.ReadLine();
Upvotes: 0
Reputation: 2287
Your need to prompt the user to re-enter the name in the loop:
String sName;
Console.Write("Enter a name (or XXX to end): ");
sName = Console.ReadLine();
while (sName != "XXX")
{
Console.Write("The Name is: " + sName);
Console.WriteLine();
Console.Write("Enter a name (or XXX to end): ");
sName = Console.ReadLine();
}
Upvotes: 0
Reputation: 223422
Your input statement should be in the loop, otherwise you will end up with an infinite loop if the first input is not equal to XXX
String sName="";
while (sName != "XXX")
{
Console.Write("Enter a name (or XXX to end): ");
sName = Console.ReadLine();
Console.Write("The Name is: " + sName);
Console.WriteLine();
}
Console.WriteLine("You are now past the while loop");
Console.WriteLine("Press any key to close");
Console.ReadKey();
Upvotes: 7