How to check if an integer is in a given range?

Solution 1:

You could add spacing ;)

if (i > 0 && i < 100) 

Solution 2:

For those using commons lang an option is to use Range:

Range<Integer> myRange = Range.between(100, 500);
if (myRange.contains(200)){
    // do something
}

Also see: how to construct a apache commons 3.1 Range<Integer> object

Solution 3:

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:

ValueRange range = java.time.temporal.ValueRange.of(minValue, maxValue);
range.isValidIntValue(x);
  • it returns true if minValue <= x <= MaxValue - i.e. within the range
  • it returns false if x < minValue or x > 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