package candy; import java.util.Random; /** * A machine that dispenses gumballs. * * @author Samuel A. Rebelsky * @version 1.0 of August 2004 */ public class GumballMachine implements CandyMachine { // +---------------+----------------------------------------------------- // | Static Fields | // +---------------+ /** * Colors of gumballs. */ String[] colors = { "Yellow", "White", "Green", "Red", "Blue" }; // +--------+------------------------------------------------------------ // | Fields | // +--------+ /** * The number of balls remaining in the machine. */ int ballsleft; /** * A random number generator, used to select balls. */ Random rng; // +--------------+------------------------------------------------------ // | Constructors | // +--------------+ /** * Build a new Gumball machine with the default number of * balls. */ public GumballMachine() { this.rng = new Random(); // 40 to 50 balls. this.ballsleft = 40 + this.rng.nextInt(11); } // GumballMachine() // +----------+---------------------------------------------------------- // | Mutators | // +----------+ /** * Get a piece of candy. * * @exception CandyMachineException * If unable to return a piece of candy (e.g., if empty). */ public String get() throws CandyMachineException { if (this.ballsleft <= 0) throw new EmptyMachineException(); else { --this.ballsleft; return colors[this.rng.nextInt(colors.length)]; } // else } // get() // +-----------+--------------------------------------------------------- // | Observers | // +-----------+ /** * Determine if the jar is empty. */ public boolean isEmpty() { return (this.ballsleft <= 0); } // isEmtpy() } // interface CandyMachine