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.

>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!");

Leave a Reply