0
votes

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
3
You never prompt the user for input in your while loop, so sName will never equal "XXX". How do you expect the loop to exit if the condition is never met? :) - Tim
Move sName = Console.ReadLine(); within the loop. - Candide
You never get new input, so sName will always be whatever was entered the first time. Try entering "XXX" on the first prompt.\ - Mike G
Then the loop will never be entered - which defeats the purpose of the exercise OP is trying to complete. - Tim
@Candide Thanks, just tried it, Also thanks everyone else for the replies. - user2945651

3 Answers

7
votes

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();
0
votes

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();
}
0
votes

you are not prompting the user for next input. Add following statement in your while loop

sName = Console.ReadLine();