How to check if an integer is in a given range?
JavaComparisonJava Problem Overview
Hoping for something more elegant than
if (i>0 && i<100)
Java Solutions
Solution 1 - Java
You could add spacing ;)
if (i > 0 && i < 100)
Solution 2 - Java
For those using commons lang an option is to use Range:
Range<Integer> myRange = Range.between(100, 500);
if (myRange.contains(200)){
// do something
}
Solution 3 - Java
I think
if (0 < i && i < 100)
is more elegant. Looks like maths equation.
If you are looking for something special you can try:
Math.max(0, i) == Math.min(i, 100)
at least it uses library.
Solution 4 - Java
ValueRange range = java.time.temporal.ValueRange.of(minValue, maxValue);
range.isValidIntValue(x);
- it returns
true
ifminValue <= x <= MaxValue
- i.e. within the range - it returns
false
ifx < minValue
orx > maxValue
- i.e. out of range
Use with if
condition as shown below:
int value = 10;
if (ValueRange.of(0, 100).isValidIntValue(value)) {
System.out.println("Value is with in the Range.");
} else {
System.out.println("Value is out of the Range.");
}
The below program checks, if any of the passed integer value in the hasTeen
method is within the range of 13 (inclusive) to 19 (inclusive).
import java.time.temporal.ValueRange;
public class TeenNumberChecker {
public static void main(String[] args) {
System.out.println(hasTeen(9, 99, 19));
System.out.println(hasTeen(23, 15, 42));
System.out.println(hasTeen(22, 23, 34));
}
public static boolean hasTeen(int firstNumber, int secondNumber, int thirdNumber) {
ValueRange range = ValueRange.of(13, 19);
System.out.println("*********Int validation Start ***********");
System.out.println(range.isIntValue());
System.out.println(range.isValidIntValue(firstNumber));
System.out.println(range.isValidIntValue(secondNumber));
System.out.println(range.isValidIntValue(thirdNumber));
System.out.println(range.isValidValue(thirdNumber));
System.out.println("**********Int validation End**************");
if (range.isValidIntValue(firstNumber) || range.isValidIntValue(secondNumber) || range.isValidIntValue(thirdNumber)) {
return true;
} else
return false;
}
}
OUTPUT
> true
as 19 is part of range
>
> true
as 15 is part of range
>
> false
as all three value passed out of range
Solution 5 - Java
I think its already elegant way for comparing range. But, this approach cause you to write extra unit tests to satisfy all &&
cases.
So, you can use any of the below approach to avoid writing extra unit tests.
Using Java 8 Streams:
if(IntStream.rangeClosed(0,100).boxed().collect(Collectors.toList()).contains(i))
Using Math class:
if(Math.max(0, i) == Math.min(i, 100))
Personally I recommend the second approach because it won't end up creating an Array of the size equal to the range you want to check.
Solution 6 - Java
I don't see how that's not elegant, but if you repeat the expression often, then it's a good idea to put it into a method, e.g.
class MathUtil
{
public static boolean betweenExclusive(int x, int min, int max)
{
return x>min && x<max;
}
}
This is particularly true if you mix exclusive and inclusive comparisons. The method name can help avoid typos, such as using < when <= should have been used. The method can also take care of ensuring that min < max etc..
Solution 7 - Java
If you're looking for something more original than
if (i > 0 && i < 100)
you can try this
import static java.lang.Integer.compare;
...
if(compare(i, 0) > compare(i, 100))
Solution 8 - Java
This guy made a nice Range class.
Its use however will not yield nice code as it's a generic class. You'd have to type something like:
if (new Range<Integer>(0, 100).contains(i))
or (somewhat better if you implement first):
class IntRange extends Range<Integer>
....
if (new IntRange(0,100).contains(i))
Semantically both are IMHO nicer than what Java offers by default, but the memory overhead, performance degradation and more typing overall are hadly worth it. Personally, I like mdma's approach better.
Solution 9 - Java
if ( 0 < i && i < 100)
if ( 'a' <= c && c <= 'z' )
Solution 10 - Java
Google's Java Library Guava also implements Range:
import com.google.common.collect.Range;
Range<Integer> open = Range.open(1, 5);
System.out.println(open.contains(1)); // false
System.out.println(open.contains(3)); // true
System.out.println(open.contains(5)); // false
Range<Integer> closed = Range.closed(1, 5);
System.out.println(closed.contains(1)); // true
System.out.println(closed.contains(3)); // true
System.out.println(closed.contains(5)); // true
Range<Integer> openClosed = Range.openClosed(1, 5);
System.out.println(openClosed.contains(1)); // false
System.out.println(openClosed.contains(3)); // true
System.out.println(openClosed.contains(5)); // true
Solution 11 - Java
if(i <= 0 || i >=100)
It will work.
Solution 12 - Java
That's how you check is an integer is in a range. Greater than the lower bound, less than the upper bound. Trying to be clever with subtraction will likely not do what you want.
Solution 13 - Java
Use this code :
if (lowerBound <= val && val < upperBound)
or
if (lowerBound <= val && val <= upperBound)
Solution 14 - Java
if you are using Spring data you can also use the Range object from Spring.
range = new org.springframework.data.domain.Range(3, 8);
range.contains(5) // will return true.
Solution 15 - Java
Just my 2 cts
// Exclusive
public boolean isOrdered(int n1, int n2, int n3) {
return n1 < n2 && n2 < n3 ;
}
call it like to see it is one of 1 to 99
if (isOrdered(0,i,100))
Solution 16 - Java
Try:
if (i>0 && i<100) {}
it will work at least ;)
Solution 17 - Java
If you are confident that numbers are stored in 2's complement form:
return ((x-low) <= (high-low));
A more general and safer solution would be:
return ((x-high)*(x-low) <= 0);
Solution 18 - Java
Range<Long> timeRange = Range.create(model.getFrom(), model.getTo());
if(timeRange.contains(systemtime)){
Toast.makeText(context, "green!!", Toast.LENGTH_SHORT).show();
}
Solution 19 - Java
if (i in 0..100) {}
please try this for efficient code ;)
Solution 20 - Java
If you just want to test whether the value of i
is in the range [0..100), and you want the boolean result, then
i >= 0 && i < 100
is fine and will give you true
or false
. If you are willing to throw an exception if the value is out of range, you can use the built-in checkIndex method
Objects.checkIndex(i, 100)
which will throw IndexOutOfBoundsException
if out of range. Granted, it is not a general solution, and is really only prettier if your context is one in which your range check is being done for checking array bounds, but it has the advantage of not needed any third party libraries, which is nice for small programs.