Reputation: 21
I want to check t1, t2 and t3 to see if they in the range of 13 - 19. If at least one of the the three are then I want to return true, if none of them are I want to return false. This code works but I wanted to know if there was a more succinct way of writing it, something maybe like:
if (t1 || t2 || t3 >13 && <19) return true else return false?
Here's my current code.
public class NumberChecker {
public static boolean hasNumber(int t1, int t2, int t3) {
if ( (t1 >=13 && t1 <=19) || (t2 >=13 && t2 <=19) || (t3 >=13
&& t3 <=19) ) {
return true;
} else return false;
}
}
Cheers
Upvotes: 1
Views: 97
Reputation: 361849
You could use a stream and an anonymous lambda function to do the match in one line:
return IntStream.of(t1, t2, t3).anyMatch(t -> t >= 13 && t <= 19);
Or you could use varargs to automatically build an array from the arguments:
public static boolean hasNumber(int... ts) {
for (int t: ts) {
if (t >= 13 && t <= 19) {
return true;
}
}
return false;
}
(answers courtesy of @shmosel)
Upvotes: 0
Reputation: 361849
Whenever you find yourself writing if (x) return true; else return false;
, realize that you can replace it with the shorter and equivalent return x;
. It may seem weird at first, but boolean conditions can be returned directly. You don't need to check if they're true and then return true.
public static boolean hasNumber(int t1, int t2, int t3) {
return (t1 >=13 && t1 <=19) || (t2 >=13 && t2 <=19) || (t3 >=13 && t3 <=19);
}
You might then choose to extract the common range check logic into a helper method. It makes the code a bit longer, but less redundant. Up to you if you like this version better; it's an aesthetic decision, really.
public static boolean hasNumber(int t1, int t2, int t3) {
return isInRange(t1) || isInRange(t2) || isInRange(t3);
}
private static boolean isInRange(int t) {
return t >= 13 && t <= 19;
}
Upvotes: 3