While or and not equal to not working?
24,415
Solution 1
If you want to come out of the loop, when the User enters Exit
or Test
then you need the &&
operator not ||
while ((var_app_choice != "Exit") && (var_app_choice != "Test"))
{
var_app_choice = Console.ReadLine();
//stuff
}
Solution 2
I think you want and not or...
If the value of var_app_choice
is "Test", then the first condition is true and the loop will execute. Similarly, if it's "Exit", then the second condition is true. In other words, you have an infinite loop...
Author by
chilly8063
Updated on July 09, 2022Comments
-
chilly8063 almost 2 years
Im quite new to C# and am trying to write a super simple loop
while ((var_app_choice != "Exit") || (var_app_choice != "Test")) { //stuff }
I have a console application where an end user will input a value
If this value is not equal (!=) to Exit OR Test then it should loop.
What am i doing wrong here?
Thanks
-
Admin over 11 yearsHere is my answer from a very similar question. It deals with a different implementation (IE conditionals, not C#), but the logic/reasoning is the same ..
-
-
chilly8063 over 11 yearsI think I need more sleep! This is exactly what I was looking for, thanks!
-
Habib over 11 years@user1718989, you are welcome, and Welcome to StackOverflow :)
-
Jeppe Stig Nielsen over 11 yearsAccording to De Morgan's law this can also be written:
while (!(var_app_choice == "Exit" || var_app_choice == "Test")) { ... }
. The "not" operator!
has been "pulled out", and "and" changed to "or". -
Jeppe Stig Nielsen over 11 yearsI agree your version is most clear. I just wanted to give another formal expression of "the choice is not Exit or Test".