3

For some reason a sentinel value will not work as expected

public static int play() {
        String input;int result;
        do {
        input = JOptionPane.showInputDialog("Do you want to play-Enter 1 if yes , 0 if no");
        result = Integer.parseInt(input);
        } while (result != 1 || result != 0);
        return result;
    }

This code above never works but it works just fine if i change the condition from while (result != 1 || result != 0); to while (result < 0 || result > 1);

Why is that so and how can i make not equal work in a do...while loop in java ?

Thanks

user2650277
  • 6,289
  • 17
  • 63
  • 132
  • 1
    In college, my professor said that "coding by brownian motion" is the root of all evil. Seek to understand why your program is doing anything at all rather than approaching it from the perspective of: "When I move this over there, the program behavior is changed". While the program isnt right, make a random change, retest. When complete, submit assignment. BAD programmer! no biscuit. – Eric Leschinski Oct 24 '14 at 18:01
  • 2
    http://mathworld.wolfram.com/deMorgansLaws.html – Karl Knechtel Oct 24 '14 at 18:02
  • `while(true)` with `if(result == 1 || result == 0) break;` is far more readable IMO. – But I'm Not A Wrapper Class Oct 24 '14 at 18:12

2 Answers2

9

Use:

while (result != 1 && result != 0) {...}

This will execute the code, ONLY if result is NOT 0 or 1


In your example, the boolean statement in the while loop will ALWAYS be equal to true because result can be equal to only 1 value:

while (result != 0 || result != 1)

If result is 1, then it is not equal to 0, if it is 0, then it can't be 1, so it will ALWAYS be true

Victor2748
  • 4,149
  • 13
  • 52
  • 89
1

while (result != 1 || result != 0)

This condition means it will always loop even with '1' or '0' as a response:

If the user enters 0, which should be valid, it will satisfy result != 1 and return true.

If the user enters 1, which should be valid, it will satisfy result != 0 and return true.


You need to use while (result != 1 && result != 0).

This will loop only if the answer is both not equals to 1 and not equals to 0.

DagdA
  • 484
  • 1
  • 7
  • 25