user2917100
user2917100

Reputation:

Checking if string is not equal to something is not working

Why isn't this working? The while loop won't end even when the value of answer is "Y" or "N" (I checked in the debugger) and I keep getting the Invalid Input message.

        Console.Write("\nYes or No(Y or N): ");

        string answer = Console.ReadLine();

        while(!answer.Equals("Y") || !answer.Equals("N"))
        {
            invalidInput();
            answer = Console.ReadLine();
        }

Upvotes: 0

Views: 100

Answers (3)

paparazzo
paparazzo

Reputation: 45096

A string can never be equal to two different strings. One or both of answer.Equals("Y") answer.Equals("N") will be false every time. With ! || the overall expression will true every time.

I think you are looking for

!answer.Equals("Y") && !answer.Equals("N")

Or

!(answer.Equals("Y") || answer.Equals("N"))

Upvotes: 1

MatSnow
MatSnow

Reputation: 7517

You can put the two conditions in brackets. The following example is also case-insensitive.

Console.Write("\nYes or No(Y or N): ");
string answer = Console.ReadLine();
while (!(answer.ToUpper().Equals("Y") || answer.ToUpper().Equals("N")))
{
    invalidInput();
    answer = Console.ReadLine();
}

Upvotes: 1

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

In order to avoid such errors (|| instead of &&) put it like this:

  // StringComparer.OrdinalIgnoreCase - let's ignore case and accept "n" or "YES"
  Dictionary<string, bool> validAnswers = new Dictionary<string, bool>(
    StringComparer.OrdinalIgnoreCase) {
       { "Y" , true},
       { "N", false},
       { "Yes" , true},
       { "No", false},
       // Add any other responses here, say {"OK", true}
  };

  Console.Write("\nYes or No(Y or N): ");

  bool answer = false;

  // Keep asking while answer is not valid one
  // .Trim() - let's be nice and allow leading and trailing spaces
  while (!validAnswers.TryGetValue(Console.ReadLine().Trim(), out answer)) {
    invalidInput();
  } 

Upvotes: 4

Related Questions