javalogical-operatorsboolean-logiccoding-efficiency

Is there any better way to write this piece of code?


I am a beginner in this, I was curious if i can write the below code more efficiently. I can't use loops or conditional statements, just logical operators.

        double a = Double.parseDouble(args[0]);
        double b = Double.parseDouble(args[1]);
        double c = Double.parseDouble(args[2]);

        boolean check = a * a + b * b == c * c || a * a + c * c == b * b
                || b * b + c * c == a * a;
        StdOut.println(a > 0 && b > 0 && c > 0 && check);

I tried the below code but there was a problem that even if the value (a,b,c) was negative, it kept resulting in true for this command-line argument:(-3 4 -5) idk why.

        double a = Double.parseDouble(args[0]);
        double b = Double.parseDouble(args[1]);
        double c = Double.parseDouble(args[2]);

        boolean check = a > 0 && b > 0 && c > 0 && a * a + b * b == c * c || a * a + c * c == b * b
                || b * b + c * c == a * a;
        StdOut.println(check);

Solution

  • Due to operator precedence, this expression:

    a > 0 && b > 0 && c > 0 && a * a + b * b == c * c || a * a + c * c == b * b || b * b + c * c == a * a
    

    Is treated as:

    (a > 0 && b > 0 && c > 0 && a * a + b * b == c * c) || (a * a + c * c == b * b) || (b * b + c * c == a * a)
    

    So it is the OR of three conditions. That's not your intended grouping, so you have to add parentheses manually.

    a > 0 && b > 0 && c > 0 && (a * a + b * b == c * c || a * a + c * c == b * b || b * b + c * c == a * a)