HIDE NAV

Coin Flip with Math.random()

The below command line program demonstrates the use of Math.random() to simulate a coin flip.
The method Math.random() generates a double type variable with a value between zero (inclusive) and one (exclusive) with all numbers equally probable.
For more information visit the Core Java API page for the class java.util.Math.

Main.java


package ceccs;

public class Main {

    public static void main(String[] args) {
        int headcount = 0;
        int i = 0;
        while (i < 1000000) {
            double randNum = Math.random();
            if (randNum < .5) {
                System.out.println("heads");
                headcount++;
            } else {
                System.out.println("tails");
            }
            i++;
        }
        System.out.println("--------------------");
	System.out.println("heads count:" + headcount);
    }

}