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 translated to a more complex statement:

I’m going to take a random double between 0.0 and 1.0, and multiply this number by maxVal, which has been cast to a double. This result should be a random double between 0.0 and maxVal, which I will then pass to Math.floor( ) and cast to an int.

While the previous statement does achieve the same task as RandomUtils, it does so by rolling-up multiple statements into a single line of code: two casts, a call to floor( ), a call to random() , and a multiplication. You may be able to instantly recognize this pattern as code that retrieves a random integer, but someone else may have a completely different approach. When you start to use some of the smaller utilities from Jakarta Commons systemwide, an application will tend toward greater readability; these small reductions in conceptual complexity quickly add up.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.107.85