Java Reference
In-Depth Information
Q: Why not just use while loops exclusively, then?
A: I suppose you could; however, in many situations, a do/while loop
or a for loop can make code more readable or make a repetition
problem easier to solve. The upcoming RandomLoop program is a
good example of a do/while loop solving a problem more effi-
ciently than a while loop. Study this program and try to determine
what the do/while loop is doing.
The RandomLoop program uses the Math.random() function to generate
random numbers. The return value of Math.random() is a random double
between 0 and 1 (but never equal to 0 or 1). Multiplying this result by 10
gives you a random number r in the range 0 < r < 10. Adding 1 changes
this range to 1 < r < 11. Casting this value to an int gives you a random
integer between 1 and 10 (including 1 and 10).
public class RandomLoop
{
public static void main(String [] args)
{
int a, b;
a = (int) (Math.random() * 10 + 1);
System.out.println(“a = “ + a);
do
{
b = (int) (Math.random() * 10 + 1);
System.out.println(“Trying b = “ + b);
}while(a == b);
System.out.println(“a = “ + a + “ and b = “ + b);
}
}
The RandomLoop program starts by declaring two ints, a and b. The vari-
able a is assigned to a random number between 1 and 10, and this number is
displayed. Inside the do/while loop, b is also assigned to a random number
between 1 and 10, and this value is displayed. If a is equal to b, the loop
repeats. This means that the loop repeats until b is not equal to a.
Therefore, when a and b are displayed after the do/while loop, it is assured
that they are two random but different numbers between 1 and 10. Figure 3.5
shows some sample outputs of the RandomLoop program.
Search WWH ::




Custom Search