0

I have this loop statement, which I'll express using C-like syntax (C, C++, Java, JavaScript, PHP, etc. all use similar syntax):

while (c != 'o' || c != 'x') {
    c = getANewValue();
}

I want it to run until I get a 'o' or 'x', but it never exits, even when c is 'o' or 'x'. Why not?

I've also tried using if:

if (c != 'o' || c != 'x') {
    // Show an error saying it must be either 'o' or 'x'
}

but that also always shows the error message, even when c is 'o' or 'x'. Why?

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Jason J.Y. Kim
  • 183
  • 2
  • 12

5 Answers5

11

The condition (c != 'o' || c != 'x') can never be false. If c is 'o', then c != 'x' will be true and the OR condition is satisfied. If c is 'x', then c != 'o' will be true and the OR condition is satisfied.

You want && (AND), not || (OR):

while (c != 'o' && c != 'x') {
    // ...
}

"While c is NOT 'o' AND c is NOT `'x'..." (e.g., it's neither of them).

Or use De Morgan's law, covered here:

while (!(c == 'o' || c == 'x')) {
    // ...
}

"While it's NOT true that (c is 'o' or c is 'x')..."

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
3

It must be if(c!='o' && c!='x') instead of if(c!='o' || c!='x'). If you use the or operator the boolean expression will be always true.

Petar Minchev
  • 46,889
  • 11
  • 103
  • 119
2

Why is my c != 'o' || c != 'x' condition always true?

The expression combines two sub-expressions using the logical OR operator (||). The expression is true if at least one of the sub-expressions is true. In order to be false, both sub-expressions it connects must be false.

The sub-expressions are c != 'o' and c != 'x'.

The first sub-expression c != 'o' is false when c == 'o'. The same for the second one; it is false when c == 'x'.

Please note that they cannot be false on the same time because c cannot be 'o' and 'x' on the same time.

axiac
  • 68,258
  • 9
  • 99
  • 134
0

The condition should be if(!(c=='o' || c=='x')) or if(c!='o' && c!='x')

Michael Gantman
  • 7,315
  • 2
  • 19
  • 36
0

even when you enter x or you enter o in that case if condition evaluates to true and hence game_start remains false.

it should be if(c!='o' && c!='x') or use a more straight forward way

if(c == 'o' || c == 'x')
   game_start=true;
else
    System.out.println("you can only enter o or x!");
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
annu
  • 75
  • 6