Java provides the Math.random()
method as well as the newer
java.util.Random
class.
The Math.random()
method
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 muliplying and translate the bottom value 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.
The java.util.Random
class described below 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).
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 whenever you want 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 x = new Random(); // default seed comes from system time. Random x = new Random(long seed); // for reproducible testing
These constructors work fine, except you have to be very careful not to create more than one Random object right at the "same time". If you do, they will both start with the same random seed, and they will both produce the same sequence of random numbers.
The most common methods are those which get the next random number.
These methods all return a uniform distribution of values, except
nextGaussian()
.
In all of these examples, x is a Random object.
int x.nextInt(int n) // returns random int >= 0 and < n int x.nextInt() // returns random int (full range) long x.nextLong() // returns random long (full range) float x.nextFloat() // returns random float >= 0.0 and < 1.0 double x.nextDouble() // returns random double >=0.0 and < 1.0 boolean x.nextBoolean() //returns random double (true or false) double x.nextGaussian() //returns random number with mean 0.0 // and standard deviation 1.0
You can create any color with values for red, green, and blue (the RGB system) between 0-255. You could do it this way:
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 will return an independent random number.