8.4. Generating Random Variables
Problem
J2SE 1.4 includes a
java.lang.Math
class that provides a mechanism to get a random
double
value between 0.0
and
1.0
, but you need to create random
boolean
values, or random int
variables between zero and a specified number.
Solution
Generate random variables with Commons Lang
RandomUtils
, which provides a mechanism to
generate random int
, long
,
float
, double
, and
boolean
variables. The following code generates a
random integer between zero and the value specified in the parameter
to nextInt( )
:
import org.apache.commons.lang.math.RandomUtils; // Create a random integer between 0 and 30 int maxVal = 30; int randomInt = RandomUtils.nextInt( maxVal );
Or, if your application needs a random
boolean
variable, create one with a call to the static method
nextBoolean( )
:
import org.apache.commons.lang.math.RandomUtils; boolean randomBool = RandomUtils.nextBoolean( );
Discussion
A frequent argument for not using a utility like
RandomUtils
is that the same task can be achieved with only one line of code. For
example, if you need to retrieve a random integer between 0 and 32,
you could write the following code:
int randomInt = (int) Math.floor( (Math.random( ) * (double) maxVal) );
While this statement may seem straightforward, it does contain a
conceptual complexity not present in
RandomUtils.nextInt(maxVal)
.
RandomUtils.nextInt(maxVal)
is a simple statement:
“I need a random integer between 0 and
maxVal
“; the statement without
RandomUtils
is ...
Get Jakarta Commons Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.