Skip to content
Advertisement

simple java program returning incorrect value

Hello I am brushing up on Java practice. I have this very simple program: There are two int values, along with a boolean variable.

i) The program will return true if one of these values is negative and one is positive.

ii) However, if the boolean variable is true, the program can only return true if both int values are negative.

I have tested this out with a bunch of int values but the program seems to break once I give the method the values of (1, -1), along with the boolean value set to true. Any help or explanation would be much appreciated.

   public static void main(String[] args) {
        System.out.println(posNeg(1,-1,true));
    }
    
    public static String posNeg(int a, int b, boolean negative){
        if(negative && (a<0 && b<0)){
            return "true";
        }else if(!negative && (a<0 && b>0) || (a>0 && b<0)){
            return "true";
        }
        return "false";
    }

Advertisement

Answer

Your code breaks because of && priority.

Wrap || condition in brackets:

public static void main(String[] args) {
    System.out.println(posNeg(1,-1,true));
}

public static String posNeg(int a, int b, boolean negative){
    if(negative && (a<0 && b<0)){
        return "true";
    }else if(!negative && ((a<0 && b>0) || (a>0 && b<0))){
        return "true";
    }
    return "false";
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement