Java Random coin tossing

Introduction

Write an application that simulates coin tossing.

Count the number of times each side of the coin appears.

Display the results.

import java.util.Random;

public class Main {
  private static final Random randomNumber = new Random();
  private static int HEADS = 0, TAILS = 1;

  public static void main(String[] args) {
    int sideCoin = -1;

    int head = 0;
    int tail = 0;

    for (int i = 0; i < 100; i++) {
      int number = randomNumber.nextInt(2);

      switch (number) {
      case 0:/*from w w w .  java2s.c  o  m*/
        sideCoin = HEADS;
        break;
      case 1:
        sideCoin = TAILS;
        break;
      }

      if (sideCoin == HEADS)
        ++head;
      else
        ++tail;
    }

    System.out.println("Heads\tTails");
    System.out.printf(" %d\t% d%n", head, tail);
  }

}



PreviousNext

Related