/* An instance of this class represents a coin that can be tossed, ** (randomly) resulting in either HEADS or TAILS. ** It augments the capability of its predecessor class (TossableCoin1) ** by keeping track of how many times each of Heads and Tails was tossed. */ public class TossableCoin2 { // instance variables // ------------------ private boolean headsShowing; // true if HEADS, false if TAILS private int headsCntr; // # times Heads was tossed private int tailsCntr; // # times Tails was tossed /* Initializes this tossable coin to be "showing" HEADS. */ public TossableCoin2() { headsShowing = true; headsCntr = 0; // not necessary, as zero is the default value tailsCntr = 0; // " } // observers // --------- /* Reports whether this coin is showing HEADS. */ public boolean isHeads() { return headsShowing; } /* Reports whether this coin is showing TAILS. */ public boolean isTails() { return !headsShowing; } /* Returns the number of times this coin has been tossed, ** with Heads being the result. */ public int headsCount() { return headsCntr; } /* Returns the number of times this coin has been tossed, ** with Tails being the result. */ public int tailsCount() { return tailsCntr; } /* Returns the number of times this coin has been tossed. */ public int tossCount() { return headsCount() + tailsCount(); } /* Returns a string indicating which of the two faces ** is "showing". */ public String toString() { String result; if (isHeads()) { result = "HEADS"; } else { result = "TAILS"; } return result; } // mutators // -------- /* Tosses this coin. */ public void toss() { headsShowing = Math.random() < 0.5; if (headsShowing) { headsCntr = headsCntr + 1; } else { tailsCntr = tailsCntr + 1; } } }