I've seen in another question that the solution to finding if your number is in a range was,
Math.abs(num1-num2) <= inRange
Where inRange is the number you are trying to figure out if it is in range between num2 and num1.
Where this formula breaks for me is when I insert these numbers.
Math.abs(25-(-25)) <= -5
I'm trying to find if -5 is in between -25 and 25. This equation is false even though the answer is true, -5 falls between -25 and 25.
Please clarify for me!
ValueRange. of(minValue, maxValue); range. isValidIntValue(x); it returns true if minValue <= x <= MaxValue - i.e. within the range.
Range = Max – Min. Coefficient of Range = (Max – Min) / (Max + Min)
The abs() method returns the absolute (positive) value of a number.
between() is a static method of the Range which is used to obtain an instance of Range with the specified minimum and maximum value. The specified minimum and maximum values are inclusive in nature.
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.
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