I am flipping two coins and the first coin that produces three HEADS in a row wins. The programme should terminate after a coin reaches this goal. And I want to know which coin it was and print a statement saying ie either Coin1 or Coin2 won the race. I can flip them OK and count to three with my two counters headCount1 and headCount2. Problem is I cant pinpoint which coin it was that actually won. Thanks for helping and here is my code:
//FlipRace.java public class FlipRace { public static void main (String[] args) { int headCount1 = 0, headcount2 = 0; Coin Coin1 = new Coin(); Coin Coin2 = new Coin(); while (headCount1 < 3 && headCount2 < 3) { Coin1.flip(); Coin2.flip(); System.out.println ("Coin1: " + Coin1); System.out.println ("Coin2: " + Coin2); if (Coin1.isHeads()) headCount1++; if (Coin2.isHeads()) headCount2++; } System.out.println ("A headCount attained 3. (Coin was flipped" + " heads 3 times in a row."); } }
And the main class:
//Coin.java //Represents a coin with two sides that can be flipped. public class Coin { private final int HEADS = 0; private final int TAILS = 1; private int face; //sets up the coin by flipping it initially. public Coin () { flip(); } //flips the coin by randomly choosing a face value. public void flip () { face = (int) (Math.random() * 2); } //returns true if the current face of the coin is heads. public boolean isHeads () { return (face == HEADS); } //returns the current face of the coin as a string. public String toString() { String faceName; if (face == HEADS) faceName = "Heads"; else faceName = "Tails"; return faceName; } }