Java Coin Flip


 

Java Coin Flip

In this section, we are going to toss a coin programmatically.

In this section, we are going to toss a coin programmatically.

Java Coin Flip

Coin Flipping is basically a interpretation of a chance outcome as the expression of divine. A coin should always have two sides. In this section, we are going to toss a coin programmatically. We have created a program that can toss a coin over and over until it comes up head 10 times. It should also record the number of tails. For this, we have used Math.random() method to generate either Head or Tail randomly. This will continue until we get ten heads.

Here is the code:

class Toss {
	public final int HEADS = 0;
	static int countH = 0;
	static int countT = 0;

	private static int face;

	public static void flip() {
		face = (int) (Math.random() * 2);
	}

	public String toString() {
		String faceName;
		if (face == HEADS) {
			faceName = "Heads";
			countH++;
		} else {
			faceName = "Tails";
			countT++;
		}
		return faceName;
	}

	public static void main(String[] args) {
		System.out.println("Outcomes:");
		do {
			flip();
			System.out.println(new Toss().toString());
		} while (countH != 10);
		System.out.println("Number of Tails: " + countT);
	}
}

Output:

Outcomes:
Heads
Tails
Tails
Tails
Tails
Heads
Heads
Tails
Tails
Heads
Heads
Heads
Heads
Heads
Tails
Tails
Tails
Heads
Tails
Heads

Number of Tails: 10

Ads