Java Program to Toss a Coin

Java 8Object Oriented ProgrammingProgramming

Let’s say we have a coin and 10 chances. Here, we will first initialize the values for head, tail and chances −

int heads = 0;
int tails = 0;
int chances = 10;

Now, we will get the head and tail values using the Random object −

for (int i = 1; i<= chances; i++) {
   if (t.chanceFunc().equals("tails")) {
      tails++;
   } else {
      heads++;
   }
}

Above, the function chanceFunc() is having Random class with the nextInt() method to get the next random value. The condition is checked and the heads and tails values are returned −

public String chanceFunc() {
   Random r = new Random();
   int chance = r.nextInt(2);
   if (chance == 1) {
      return"tails";
   } else {
      return"heads";
   }
}

Example

 Live Demo

import java.util.Random;
class Toss {
   public String chanceFunc() {
      Random r = new Random();
      int chance = r.nextInt(2);
      if (chance == 1) {
         return"tails";
      } else {
         return"heads";
      }
   }
}
public class Demo {
   public static void main(String[] args) {
      Toss t = new Toss();
      int heads = 0;
      int tails = 0;
      int chances = 10;
      for (int i = 1; i<= chances; i++) {
         if (t.chanceFunc().equals("tails")) {
            tails++;
         } else {
            heads++;
         }
      }
      System.out.println("Chances = " + chances);
      System.out.println("Heads: " + heads);
      System.out.println("Tails: " + tails);
   }
}

Output

Chances = 10
Heads: 3
Tails: 7

Let us run the program again −

Chances = 10
Heads: 4
Tails: 6
raja
Published on 24-Apr-2019 11:01:57
Advertisements