/* An instance of this class represents a coin that can be tossed, ** (pseudo-randomly) resulting in either HEADS or TAILS (with equal ** probabilities). */ public class TossableCoin { // instance variable // ----------------- private boolean headsShowing; // true if HEADS, false if TAILS /* Initializes this tossable coin to be "showing" HEADS. */ public TossableCoin() { headsShowing = true; } // 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 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 // -------- /* Simulates a tossing of this coin, which is intended to be "fair", ** meaning that each of HEADS and TAILS should result half the time. */ public void toss() { headsShowing = Math.random() < 0.5; //Note that the code above is equivalent to the more verbose // // if (Math.random()) < 0.5) // { headsShowing = true; } // else // { headsShowing = false; } } }