My friend wrote this code for an assignment in his programming class:
public class test {
public static void main(String args[]) {
double x = 0.9;
double y = 0.1;
boolean truth = x < 1 && x > 0 && y < 1 && y > 0;
System.out.println(truth);
}
}
I'm wondering (for myself) if there's a way to simplify the conditional operators in this line specifically:
boolean truth = x < 1 && x > 0 && y < 1 && y > 0;
Your only option for a one-liner is to use parenthesis. Personally, I prefer multiple statements to make things much clearer:
boolean isXInRange = x > 0 && x < 1;
boolean isYInRange = y > 0 && y < 1;
boolean truth = isXInRange && isYInRange;
No, but it might be made clearer (opinion):
boolean truth = (0 < x && x < 1 && 0 < y && y < 1);
The flipping of the zero check makes it easy to read as 0 < x < 1. Is that clearer? A very little bit.
The parenthesis is a style choice. Since boolean expressions are always parenthesized in if statements and while loops, I find it clearer to always parenthesize boolean operators.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With