Java Programming/Basic Arithmetic/Random Numbers

From Wikibooks, the open-content textbooks collection

Jump to: navigation, search

To generate random numbers the Math.random() method can be used, which returns a double, greater than or equal to 0.0 and less than 1.0.

The following code returns a random integer between n and m (where n <= randomNumber < m):

  int randomNumber = n + (int)(Math.random() * ( m - n ));

Alternatively, the java.util.Random class provides methods for generating random booleans, bytes, floats, ints, longs and 'Gaussians' (doubles from a normal distribution with mean 0.0 and standard deviation 1.0). For example, the following code is equivalent to that above:

  Random random = new Random();
  int randomNumber = n + random.nextInt(m - n);


Or:

  Random random = new Random();
  int randomNumber = random.nextInt(500); // this will return a pseudorandom int between 0 and 499

As an example using random numbers, we can make a program that uses a Random object to simulate flipping a coin 20 times:

import java.util.Random;
 
public class CoinFlipper {
 
    public static void main(String[] args) {
        final int TIMES_TO_FLIP = 20; // The number of times to flip the coin
        int heads = 0;
        int tails = 0;
        Random random = new Random(); // create a Random object
        for (int i = 0; i < TIMES_TO_FLIP; i++) {
            int result = random.nextInt(2); // 0 or 1
            if (result == 1) {
                System.out.println("Heads");
                heads++;
            } else {
                System.out.println("Tails");
                tails++;
            }
        }
        System.out.println("There were " + heads + " heads and " + tails
                + " tails");
    }
}

which could create this output:

Heads
Tails
Tails
Tails
Heads
Tails
Heads
Heads
Heads
Heads
Heads
Heads
Tails
Tails
Tails
Tails
Heads
Tails
Tails
Tails
There were 9 heads and 11 tails

Of course, if you run the program you will probably get different results.