Java Reference
In-Depth Information
Continued from previous page
that 47 % 2 does not equal 0 , so the code would proceed to the else statement.
The println statement would then execute another call on nextInt , which
would return a completely different number (say, 128 ). The output of the code
would then be the following bizarre statement:
Odd number: 128
The solution to this problem is to store the randomly chosen integer in a vari-
able and call nextInt again only if another random integer is truly needed. The
following code accomplishes this task:
// this code behaves correctly
Random r = new Random();
int n = r.nextInt(); // save random number into a variable
if (n % 2 == 0) {
System.out.println("Even number: " + n);
} else {
System.out.println("Odd number: " + n);
}
Simulations
Traditional science and engineering involves a lot of real-world interaction. Scientists
run experiments to test their hypotheses and engineers build prototypes to test their
designs. But increasingly scientists and engineers are turning to computers as a way
to increase their productivity by running simulations first to explore possibilities
before they go out and run an actual experiment or build an actual prototype. A
famous computer scientist named Jeanette Wing has argued that this increased use of
computation by scientists and engineers will lead to computational thinking being
viewed as fundamental in the same way that reading, writing, and arithmetic are con-
sidered fundamental today.
From a programming perspective, the two key ingredients in a simulation are
pseudorandom numbers and loops. Some simulations can be written using for loops,
but more often than not we use a while loop because the simulation should be run
indefinitely until some condition is met.
As a simple example, let's look at how we would simulate the rolling of two dice until
the sum of the dice is 7. We can use a Random object to simulate the dice, calling it once
for each of the two dice. We want to loop until the sum is equal to 7 and we can print the
various rolls that come up as we run the simulation. Here is a good first attempt:
 
Search WWH ::




Custom Search