How do you find if a number is within a range in Java? Problems with Math.abs(num1-num2) <= inRange

I don't see any reason to use Math.abs at all. I'd use:

if (lowerBound <= value && value < upperBound)

or

if (lowerBound <= value && value <= upperBound)

if you want the upper bound to be inclusive too.

Indeed, the Math.abs() approach seems entirely broken - I strongly suspect that you misunderstood the question where it was posed as a solution.


Just do:

bool isInRange = Math.min(num1,num2) <= inRange 
                && Math.max(num1,num2) >= inRange;

Your current approach just checks number ranges. in fact smallest and largest number distance.


For bonus points, there is a new Range class (used with helper class Ranges) introduced in Guava 10.x:

import com.google.common.collect.Range;
import com.google.common.collect.Ranges;

public class RangeTest {

    Range<Integer> range = Ranges.closed(-25, +25);

    public boolean rangeTest(Integer candidate) {
        return range.contains(candidate);
    }

}


public class TestMain {
    static RangeTest rangeTest = new RangeTest();

    public static void doTest(Integer candidate) {
        System.out.println(candidate + " in -25..+25: "
                + rangeTest.rangeTest(candidate));
    }

    public static void main(String[] args) {
        doTest(-26);
        doTest(-25);
        doTest(-24);
        doTest(-1);
        doTest(-0);
        doTest(+1);
        doTest(+24);
        doTest(+25);
        doTest(+26);
    }

}

Output:

-26 in -25..+25: false
-25 in -25..+25: true
-24 in -25..+25: true
-1 in -25..+25: true
0 in -25..+25: true
1 in -25..+25: true
24 in -25..+25: true
25 in -25..+25: true
26 in -25..+25: false

The Range class supports open and closed ranges, ranges from -INF to +INF, and all sorts of range-related operations like membership, intersection, and span.

Tags:

Java

Math