Checking user input in a loop. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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. }

4th Feb 2017, 11:58 PM
Igor Ilnicky
Igor Ilnicky - avatar
2 Answers
+ 1
set a label before requesting user input, evaluate if the input is valid, if is invalid goto label; else proceed with your code
5th Feb 2017, 12:11 AM
seamiki
seamiki - avatar
+ 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(); }
7th Feb 2017, 4:56 PM
Igor Ilnicky
Igor Ilnicky - avatar