Martin Gustafsson Martin Gustafsson - 2 months ago 6
Java Question

OR in a while statement not working

import java.util.Scanner;

public class test{
public static void main(String [] args){

Scanner in = new Scanner(System.in);
int a = 1;
int b = 1;

while (a != 0 || b != 0){
System.out.println("");
a = in.nextInt();
b = in.nextInt();

}
}
}


My question is why does "a" AND "b" need to be 0 for the while to stop?
Anything i can do to fix? I could make a new variable and then:

if (a = 0){
//blabla...
}


but i would rather not...

Answer

The condition you have currently:

while (a != 0 || b != 0)

Is the equivalent of, as @TimBiegeleisen said:

while(a == 0 && b == 0)

And, as you realized, you don't want that. Fix your condition to this:

while(!(a == 0 || b == 0))

Because this would be the condition you want.

Your complete code should be:

import java.util.Scanner;
public class test{

    public static void main(String []args){
        Scanner in = new Scanner(System.in);
        int a = 1;
        int b = 1;

        while (!(a == 0 || b == 0)){
            System.out.println("");
            a = in.nextInt();
            b = in.nextInt();
        } 
    }
}