Question:
Write a program that simulates flipping a coin 1 million times and displays the number of heads and tails.?
Code:
public class CoinFlip { public static void main(String[] args) { int heads = 0; int tails = 0; for(int x=0;x<1000000;x++){ if (Math.random() < 0.5) { tails = tails +1; } else { heads = heads +1; } } System.out.println("Heads total: " + heads); System.out.println("Tails total: " + tails); } }
Output:
$ java CoinFlip Heads total: 500298 Tails total: 499702