Two classes. Java provides the
Math.random() method as well as the
java.util.Random class. The methods of the
class often produce random numbers in a more convenient form, but
requires creating an object, which sometimes is inconvenient. In constrast, the
method produces a double value which must sometimes be translated and cast
into the form you need it. It's a tradeoff between the globalness of
Math.random more directly useful numbers from the
To use the Random class create an object of this class (giving a seed to the constructor if you wish), then call one of the methods below to get a new random number. You must use one of the following import statements:
import java.util.Random; // Only the Random class import java.util.*; // All classes in the java.util package
Random r = new Random(); // Default seed comes from system time. Random r = new Random(long seed); // For reproducible testing
The most common methods are those which return a random number.
These methods return a uniform distribution of values, except
In these examples, x is a Random object.
|Returns random int >= 0 and < n|
|Returns random int (full range)|
|Returns random long (full range)|
|Returns random float >= 0.0 and < 1.0|
|Returns random double >=0.0 and < 1.0|
|Returns random double (true or false)|
|Returns random number with mean 0.0 and standard deviation 1.0|
To create any color with values for red, green, and blue (the RGB system) between 0-255:
Random r = new Random(); Color c = new Color(r.nextInt(256), r.nextInt(256), r.nextInt(256));
Although the three calls to
nextInt(256) look the
same, each returns an independent random number.
nextInt(6) returns a number from
0-5, it's necessary to add 1 to scale the number
into the range 1-6,
static Random randGen = new Random(); int spots; . . . spots = randGen.nextInt(6) + 1;
returns random double numbers in the range >=0.0 to <1.0 .
It returns the same result as the
Random nextDouble() method (see below).
double x; x = Math.random(); // assigns random number to x
Usually the range 0.0...0.999999+ isn't what is desired so it's necessary to scale the range by multiplying and translate the values by addition. Finally, an int is commonly desired, so casting is required.
For example, if you need an int int the range 1 to 10, the following code could be used.
int n = (int)(10.0 * Math.random()) + 1;
The multiplication scales the range to 0.0 to 9.9999+, casting it to int to gets it into the integer range 0 to 9 (truncation, not rounding), then addition of 1 translates it into the range 1 to 10.
java.util.Random class has convenient
methods which do this extra work for you, but you have to create a Random
object and make sure it's accessible where you need it (sometimes awkward).