Not equal in do while loop

For some reason the value of the sentinel device 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 fine if I change the condition from while (result != 1 || result != 0);

towhile (result < 0 || result > 1);

Why is this so and how can I make unequal work in a loop do...while

in java?

thank

+3


source to share


2 answers


Using:

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

      

This will execute the code ONLY if result

NOT 0

or1




In your example, the logical operator in the loop while

will ALWAYS be equal true

, because the result can only be 1 value:

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

      

If result

- 1

, then it is not equal 0

, if it is 0

, then it cannot be 1

, therefore it will ALWAYS betrue

+6


source


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

This condition means that it will always loop even on "1" or "0" as an answer:

If the user enters 0, which should be valid, it satisfies result != 1

and returns 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 only execute if the answer is not 1, not 0.

0


source







All Articles