Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not equal to in a do while loop [duplicate]

Tags:

java

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

like image 698
user2650277 Avatar asked Oct 22 '25 16:10

user2650277


1 Answers

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

like image 85
Victor2748 Avatar answered Oct 25 '25 06:10

Victor2748