Java Reference
In-Depth Information
Finally, there is another goto ɨ like statement, the continue statement, which
jumps to the end of the current iteration of the loop. Here is a possible use for this
statement:
while (!done)
{
String input = in.next();
if (input.equalsIgnoreCase("Q"))
{
done = true;
continue; // Jump to the end of the loop body
}
double x = Double.parseDouble(input);
data.add(x);
// continue statement jumps here
}
By using the continue statement, you don't need to place the remainder of the
loop code inside an else clause. This is a minor benefit. Few programmers use
this statement.
255
256
6.5 Random Numbers and Simulations
In a simulation you generate random events and evaluate their outcomes. Here is a
typical problem that can be decided by running a simulation: the Buffon needle
experiment, devised by Comte Georgesɨ Louis Leclerc de Buffon (1707ȋ1788), a
French naturalist. On each try, a oneɨinch long needle is dropped onto paper that is
ruled with lines 2 inches apart. If the needle drops onto a line, count it as a hit. (See
Figure 3 .) Buffon conjectured that the quotient tries/hits approximates ƚ.
In a simulation, you repeatedly generate random numbers and use them to simulate
an activity.
Now, how can you run this experiment in the computer? You don't actually want to
build a robot that drops needles on paper. The Random class of the Java library
implements a random number generator, which produces numbers that appear to be
completely random. To generate random numbers, you construct an object of the
Random class, and then apply one of the following methods:
Search WWH ::




Custom Search