Java Reference

In-Depth Information

•
int nextInt()
: Returns a pseudo-random number integer. Values are uniformly distributed

across the range of possible values of type
int.

•
int nextInt(int limit)
: Returns a pseudo-random number integer that is greater than or equal

to 0, and less than
limit
— very useful for creating random array index values.

•
long nextLong()():
The same as
nextInt()
except values are of type
long
.

•
float nextFloat()
: Returns a pseudo-random
float
value. Values are uniformly distributed

across the range 0.0f to 1.0f, excluding 1.0f.

•
double nextDouble()
: Returns a pseudo-random number of type
double
. Values are uniformly

distributed across the range 0.0 to 1.0, excluding 1.0.

•
double nextGaussian()
: Returns a pseudo-random number selected from a Gaussian distribu-

tion. Values generated have a mean of 0.0 and a standard deviation of 1.0.

•
void nextBytes(byte[] bytes)
: Fills the array,
bytes
, with pseudo-random values.

•
boolean nextBoolean()
: Returns a pseudo-random
boolean
value with
true
and
false
being

equally probable.

•
void setSeed(long seed)
: Resets the random number generator to generate values using the

value passed as an argument as a starting seed for the algorithm.

To produce a pseudo-random number of a particular type, you just call the appropriate method for a
Ran-

dom
object. You can repeat a sequence of numbers that has been generated by a
Random
object with a given

seed by calling the
setSeed()
method with the original seed value as the argument.

You can give the
Random
class an outing with a simple program that simulates throwing a pair of dice.

The program allows you six throws to try to get a double six.

TRY IT OUT: Using Random Objects

Here's the program:

import java.util.Random;

import java.io.IOException;

public class Dice {

public static void main(String[] args) {

System.out.println("You have six throws of a pair of dice.\n" +

"The objective is to get a double six. Here

goes...\n");

Random diceValues = new Random();

// Random number

generator

String[] goes = {"First", "Second", "Third",

"Fourth", "Fifth", "Sixth"};

int die1 = 0;

// First die value

int die2 = 0;

// Second die

value