import java.util.Random; /* An instance of this class represents a (fair) coin that is suitable ** for simulating a sequence of coin tosses. ** ** Author: R. McCloskey ** Date: January 2024 */ public class Coin { // instance variables // ------------------ protected boolean isHeads; // true if HEADS is "showing" protected Random rand; // for producing pseudo-random numbers that // simulate coin tosses // constructors // ------------ /* Establishes this coin as one that is showing HEADS and whose toss() ** method uses a pseudo-random number generator seeded by the given value. */ public Coin(int seed) { rand = new Random(seed); isHeads = true; } /* Establishes this coin as one that is showing HEADS and whose toss() ** method uses a pseudo-random number generator seeded by a number that ** is itself generated pseudo-randomly. */ public Coin() { this((int)(20000 * Math.random())); } // observers // --------- /* Reports whether or not this coin is showing HEADS. */ public boolean isHeads() { return isHeads; } /* Reports whether or not this coin is showing TAILS. */ public boolean isTails() { return !isHeads(); } /* Returns a string indicating which face this coin is showing. */ public String toString() { String nameOfClass = this.getClass().getName(); String face = isHeads() ? "HEADS" : "TAILS"; return String.format("Class: %s; Face Showing: %s", nameOfClass, face); } // mutator // ------- /* Tosses this coin, producing each of the two possible results ** with equal probability. */ public void toss() { isHeads = rand.nextDouble() < (1.0 / 2.0); // alternative (but does not produce same result each time): //isHeads = rand.nextBoolean(); } }