Java Algorithms How to - Toss Coin








Question

We would like to know how to toss Coin.

Answer

import java.util.Random;
//  w ww  .j  a va2  s.  c o  m
class Coin {
  public String toss() {
    Random myRand = new Random();
    int face = myRand.nextInt(2);
    if (face == 0) {
      return "heads";
    } else {
      return "tails";
    }
  }
}

public class Main {
  public static void main(String[] args) {
    Coin coin = new Coin();
    int headsCount = 0;
    int tailsCount = 0;
    for (int i = 1; i <= 40; i++) {
      if (coin.toss().equals("heads")) {
        headsCount++;
      } else {
        tailsCount++;
      }
    }
    System.out.println("Total number of heads: " + headsCount
        + "\nTotal number of tails: " + tailsCount);
  }
}

The code above generates the following result.