Home Tutorial Java Core Java Coin Flip

 
 

Share on Google+Share on Google+
Java Coin Flip
Posted on: May 1, 2010 at 12:00 AM
Advertisement
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

Advertisement

Related Tags for Java Coin Flip:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: May 1, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com