/* 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 (TossableCoin3) ** in that a coin "remembers" its entire history of tosses. */ public class TossableCoin4 { // class constants // --------------- private static char HEADS = 'H'; private static char TAILS = 'T'; // 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 private double headsProb; // probability of Heads resulting from a toss private String tossHistory; // String of H's and T's recording the results // of all past tosses of this coin /* Initializes this tossable coin to be "showing" HEADS and for the ** given number to be the probability of a toss resulting in Heads. ** pre: 0 <= hProb <= 1.0 */ public TossableCoin4(double hProb) { headsShowing = true; headsCntr = 0; // not necessary, as zero is the default value tailsCntr = 0; // " headsProb = hProb; tossHistory = ""; } /* Initializes this tossable coin to be a fair one initially ** "showing" HEADS. */ public TossableCoin4() { this(0.5); } // observers // --------- /* Reports whether this coin is showing HEADS. */ public boolean isHeads() { return headsShowing; } /* Reports whether the k-th toss of this coin resulted in HEADS. */ public boolean wasHeads(int k) { return tossHistory.charAt(k-1) == HEADS; } /* Reports whether this coin is showing TAILS. */ public boolean isTails() { return !headsShowing; } /* Reports whether the k-th toss of this coin resulted in TAILS. */ public boolean wasTails(int k) { return tossHistory.charAt(k-1) == TAILS; } /* 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() < headsProb; //Notice the change from 0.5 if (headsShowing) { headsCntr = headsCntr + 1; tossHistory = tossHistory + HEADS; } else { tailsCntr = tailsCntr + 1; tossHistory = tossHistory + TAILS; } } }