Java Reference
In-Depth Information
It's also possible that the program will take a while to pick the number, as in the
following sample execution:
This program picks numbers from
1 to 10 until a particular
number comes up.
Pick a number between 1 and 10——>
10
next number = 9
next number = 7
next number = 7
next number = 5
next number = 8
next number = 8
next number = 1
next number = 5
next number = 1
next number = 9
next number = 7
next number = 10
Your number came up after 12 times
Common Programming Error
Misusing the
Random
Object
A
Random
object chooses a new random integer every time the
nextInt
method is called. When students are trying to produce a constrained random
value, such as one that is odd, sometimes they mistakenly write code such as
the following:
// this code contains a bug
Random r = new Random();
if (r.nextInt() % 2 == 0) {
System.out.println("Even number: " + r.nextInt());
} else {
System.out.println("Odd number: " + r.nextInt());
}
The preceding code fails in many cases because the
Random
object produces
one random integer for use in the
if/else
test, then another for use in
whichever
println
statement is chosen to execute. For example, the
if
test
might retrieve a random value of
47
from the
Random
object. The test would find
Continued on next page
Search WWH ::
Custom Search