Java Reference

In-Depth Information

Random random=
new
Random(long);

where
long
is any
long
integer, or

Random random=
new
Random();

In the first case, the seed used to start the sequence of random numbers is based

on argument
long
. In the second case, the seed is the time in milliseconds at

which the new-expression was evaluated.

Use the first case when testing a program because you may need to repeat

an execution in order to help find errors. Use the second case when running so

that you always use a new seed and thus get a new sequence of random numbers.

Now, whenever a new random number is generated, use one of the follow-

ing function calls. There are several possibilities because one might want to gen-

erate sequences of random values in different types and ranges:

•
random.nextBoolean() =
a
boolean
value

•
random.nextDouble() =
a
double
d
satisfying
0≤d<1

•
random.nextFloat() =
a
float
f
satisfying
0≤f<1

•
random.nextInt() =
an
int

•
random.nextInt(n) =
an
int
i
satisfying
0≤i<n

•
random.nextLong() =
a
long

Class
Random
has other instance methods, but the ones discussed above will

be used most frequently.

5.6.3

Exercises with random numbers

E1.
Write a function
oneOrTwo
that uses function
Math.random
to return a ran-

dom integer in the range
1..2
. Test it.

E2.
Function
oneOrTwo
produces either
1
or
2
, randomly. One can think of
1
as

“heads” and
2
as “tails”, so we can think of a call of function oneOrTwo as sim-

ulating a flip of a coin. If we flip a coin 100 times, or 1,000 times, we would

assume that half the tosses are “heads” and half are “tails”. Write a program to

test whether oneOrTwo is really fair, in this sense. The program will call

oneOrTwo a certain number of times and report back how many of the tosses

were “heads” and how many were “tails”. Experiment with this program.

E3.
Write a function to “throw a die (meaning one of a pair of dice)” —it should

produce an integer in the range
1..6
.

E4.
Write a program that throws a die
n
times (for some given
n
) and counts how

many times one roll is followed by exactly the same roll. E.g. the answer for the

7
-roll sequence
3, 2, 2, 4, 4, 4, 3
is
3
, since a
2
is followed by
2
, a
4
is fol-

lowed by
4
, and that
4
is followed by
4
. After you test it, experiment with it.

E5.
Write a program that rolls a die until a
6
is rolled. Print out how many rolls

Search WWH ::

Custom Search