8.3. Using Number Ranges
Problem
You need to define a range of acceptable values for a variable, and test to see if that variable is within those boundaries.
Solution
Use an implementation of Range, an interface that
defines a simple numerical range. There are a number of different
implementations for different types:
NumberRange
,
DoubleRange
,
FloatRange
,
IntRange
,
and
LongRange
. The following example demonstrates the
use of DoubleRange to verify that a variable is
within a valid range. A DoubleRange is created
with minimum and maximum values, and a value is tested by
DoubleRange using a method named
containsDouble( )
:
import org.apache.commons.lang.math.DoubleRange; import org.apache.commons.lang.math.Range;Range safeSpeed = new DoubleRange( 0.0, 65.0 );double currentSpeed = getCurrentSpeed( );if( !safeSpeed.containsDouble( currentSpeed ) ) {System.out.println( "Warning, current speed is unsafe." ); }
Discussion
Additionally, one can also test to see if another
Range is contained within a
Range, or if a Range overlaps
another Range. The following example demonstrates
the use of containsRange( )
to determine if a Range
is entirely contained within another Range:
import org.apache.commons.lang.math.Range; import org.apache.commons.lang.math.IntRange; import org.apache.commons.lang.math.NumberUtils; double recordHigh = getRecordHigh( ); double recordLow = getRecordLow( ); IntRange recordRange = new IntRange( recordLow, recordHigh ); int todayTemp = getTodaysMaxTemp( ); ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access