import java.util.Random; /** An instance of this class models a coin that can be tossed to yield ** heads or tails, with equal probability. ** ** @author R. McCloskey ** @version August 2008 */ public class TossableFairCoin { /* d a t a */ private boolean headsUp; // true means heads is showing, false means tails private Random ran; // for tossing the coin private int headsCntr; // # of heads tossed in lifetime of coin private int tailsCntr; // # of tails tossed in lifetime of coin private static final String HEADS_STR = new String("Heads"); private static final String TAILS_STR = new String("Tails"); /* c o n s t r u c t o r */ /** Initializes the coin's fields. */ public TossableFairCoin() { headsCntr = 0; tailsCntr = 0; ran = new Random(); } /* o b s e r v e r s */ /** Reports whether or not the coin is showing heads. ** @return true if the coin is showing heads, false otherwise */ public boolean isHeads() { return headsUp; } /** Reports whether or not the coin is showing tails. ** @return true if the coin is showing tails, false otherwise */ public boolean isTails() { return !isHeads(); } /** Reports the number of times during its lifetime that the coin ** has been tossed to yield heads. ** @return number of times the coin has been tossed to yield heads */ public int numHeadsTossed() { return headsCntr; } /** Reports the number of times during its lifetime that the coin ** has been tossed to yield tails. ** @return number of times the coin has been tossed to yield tails */ public int numTailsTossed() { return tailsCntr; } /** Reports the number of times during its lifetime that the coin ** has been tossed. ** @return number of times the coin has been tossed */ public int numTimesTossed() { return headsCntr + tailsCntr; } /** Returns a string indicating which side of the coin is showing, ** heads or tails. ** @return a string indicating which side of the coin is showing */ public String toString() { return isHeads() ? HEADS_STR : TAILS_STR; /* the above is equivalent to the following if statement: */ // if (isHeads()) // { return HEADS_STR; } // else // { return TAILS_STR; } } /* m u t a t o r */ /** Tosses the coin, after which there is a probability of 1/2 that ** the coin shows heads, and similarly for tails. */ public void toss() { headsUp = ran.nextBoolean(); if (isHeads()) { headsCntr++; } else { tailsCntr++; } } }