Java Reference
In-Depth Information
Display 3.11
Comparing Strings
1 import java.util.Random;
2 public class CoinFlipDemo
3 {
4 public static void main(String[] args)
5 {
6 Random randomGenerator = new Random();
7 int counter = 1;
8
9 while (counter <= 5)
10 {
11 System.out.print("Flip number " + counter + ": ");
12 int coinFlip = randomGenerator.nextInt(2);
13 if (coinFlip == 1)
14 System.out.println("Heads");
15 else
16 System.out.println("Tails");
17 counter++;
18 }
19 }
20 }
Sample Dialogue (output will vary)
Flip number 1: Heads
Flip number 2: Tails
Flip number 3: Heads
Flip number 4: Heads
Flip number 5: Tails
The Math.random() Method
Java also includes a method to generate random doubles without requiring the user to
create an instance of the Random class. The method Math.random() returns a random
double that is greater than or equal to 0.0 but less than 1.0. In fact, when this method
is called for the first time, Java internally creates an instance of the Random class and
invokes the nextDouble() method. This can be convenient if you do not want to
create your own Random object.
Often the range between 0.0 and 1.0 is not what is desired, so it becomes necessary
to scale the range by multiplying and translating the value by addition. Commonly, an
int is desired, which requires a typecast. For example, if you need an int in the range
from 1 to 6, the following code could be used:
int num = ( int )(Math.random() * 6) + 1;
 
 
Search WWH ::




Custom Search