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?
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 it’s “not 1” and it’s “not 2”.)
Or:
See De Morgan’s Laws for more transformations.