+ 1
Checking user input in a loop.
I'm trying to request an answer from user, which is defined as: string answer1 = Console.ReadLine(); Using IF and ELSE IF I can catch "Yes" or "No", but what if the answer will be completely different? I want user to receive repeated question each time he inserts a wrong answer, but unfortunately, previously defined answer1 cant be used inside WHILE loop. I tried this way: while (answer1 != "Yes" || answer1 != "No") { Console.WriteLine("Please answer 'Yes' or 'No'"); //Here I want to check second answer. }
2 Respuestas
+ 1
set a label before requesting user input,
evaluate if the input is valid,
if is invalid goto label;
else proceed with your code
+ 1
Not sure i understand it at the moment but working variant is:
string answer1 = Console.ReadLine();
while (!(answer1 == "Yes" || answer1 == "No"))
{
Console.WriteLine("\nProgram: Please answer 'Yes' or 'No'");
Console.Write("\n" + name + ": ");
answer1 = Console.ReadLine();
}