Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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);

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading