Java Reference
In-Depth Information
Use the
java.util.Random
class to help generate the random numbers. The
Ran-
dom
class was developed for the purpose of generating random numbers for a handful
of the Java numeric data types. This code demonstrates the use of
Random
to generate
such numbers:
// Create a new instance of the Random class
Random random = new Random();
// Generates a random Integer
int myInt = random.nextInt();
// Generates a random Double value
double myDouble = random.nextDouble();
// Generates a random float
float myFloat = random.nextFloat();
// Generates a random Gaussian double
// mean 0.0 and standard deviation 1.0
// from this random number generator's sequence.
double gausDouble = random.nextGaussian();
// Generates a random Long
long myLong = random.nextLong();
// Generates a random boolean
boolean myBoolean = random.nextBoolean();
Solution #2
Make use of the
Math.random()
method. This will produce a
double
value that is
greater than 0.0, but less than 1.0. The following code demonstrates the use of this
method:
double rand = Math.random();
How It Works