Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

While loop with logical operators – stuck in loop

I want "Y" or "N" to be the only valid input, which I did like this:

Console.WriteLine("Connect to the Database? Y/N");
string answer = Console.ReadLine().ToUpper();
while (answer != "Y" || answer != "N")
{
    Console.WriteLine("Incorrect Response.");
    Console.WriteLine("Connect to the Database? Y/N");
    answer = Console.ReadLine().ToUpper();
}
if (answer == "N") Environment.Exit(0);

Console.WriteLine("Successfull connection!");

But, whatever I enter as the answer, including "Y" and "N", it just loops forever.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

While saying answer != "Y" || answer != "N" you are telling C# that if at any case, answer is not equal to that, it will continue to prompt the user.
Following that logic, if answer is Y, then it is not equal to N. And in the other way, if answer is N, it is not equal to Y.
That means that in order to work, it should not be equal to Y AND to N.

Console.WriteLine("Connect to the Database? Y/N");
string answer = Console.ReadLine().ToUpper();
Console.WriteLine(answer != "Y");
Console.WriteLine(answer != "N");
while (answer != "Y" && answer != "N")
{
    Console.WriteLine("Incorrect Response.");
    Console.WriteLine("Connect to the Database? Y/N");
    answer = Console.ReadLine().ToUpper();
}
if (answer == "N") Environment.Exit(0);

Console.WriteLine("Successfull connection!");
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading