Xaisoft
Xaisoft

Reputation: 46641

What is wrong with this short-circuited if statement?

I know this is probably really dumb, but I can't figure out why this if statement is failing:

If I enter 1 or 2 at the console, the first if statement fails, but the second one passes if I first store the result in a bool first. Why? I am probably doing something dumb here?

Console.WriteLine("Enter 1 for AM or 2 for PM?"); 
string amOrPM = Console.ReadLine();

//Why does this fail if I enter 1 or 2?
if (amOrPM != "1" || amOrPM != "2") 
    Console.WriteLine("You must enter 1 for AM or 2 for PM. Try again.");

//This works!
bool valid = (amOrPM != "1" || amOrPM != "2"); 
if (!valid) 
    Console.WriteLine("You must enter 1 for AM or 2 for PM. Try again.");

I just noticed for the first if statement, I had to put && instead of ||, but this is confusing because I read it as: if amOrPm does not equal 1 or amOrPM does not equal 2, then go to the Console line. Am I reading the definition of this wrong?

Upvotes: 1

Views: 175

Answers (4)

Erik Funkenbusch
Erik Funkenbusch

Reputation: 93444

Or is a logical or. What it means is this:

if you enter 1 then the first condition is false, but the second condition is true, thus it fails.

If you enter 2, then the first condition is true, but the second is false, so it fails. There is no way for the condition to ever be false for both of them.

Upvotes: 2

Zugbo
Zugbo

Reputation: 514

You've got ! in front of valid in the second case- you're inverting the result. Remove that ! and they'll both behave the same.

Upvotes: 3

Sascha
Sascha

Reputation: 10347

The correct thing would be if (amOrPM != "1" && amOrPM != "2"). You want to write if it's neither 1 nor 2. The second works because it negating, it is either 1 or 2.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1502556

Think of it this way - if it is 1, then it can't possibly be 2, and vice versa. So it will definitely be either "not 1" or "not 2".

You mean:

if (amOrPM != "1" && amOrPM != "2") 

(If it's "not 1" and it's "not 2".)

Or:

if (!(amOrPm == "1" || amOrPm == "2"))

See De Morgan's Laws for more transformations.

Upvotes: 7

Related Questions