// Stephen's solution class VendingMachine { private int numDrPeppers, numStarbucks; private double amountInsertedByThisCustomer; private double amountInSales; /** * Create a new, fully-stocked VendingMachine object. Vending machines * begin with eight Dr. Peppers, six foofy Starbucks beverages, and $10 to * make change. */ VendingMachine() { this.numDrPeppers = 8; this.numStarbucks = 6; this.amountInsertedByThisCustomer = 0; this.amountInSales = 0; } /** * Insert the number of dollars passed as an argument into the little coin * slot. */ void insertMoney(double dollars) { this.amountInsertedByThisCustomer += dollars; } /** * Never mind -- gimme my money back. This method returns the amount of * money (in dollars) that the customer has inserted (and obviously takes * away their credit). */ double cancel() { double return_value = this.amountInsertedByThisCustomer; this.amountInsertedByThisCustomer = 0; return return_value; } /** * Buy a Dr Pepper, and return the amount of change (in dollars) owed to * the customer. (Dr Peppers cost $1.25.) If there are no more Dr Peppers * in the machine, or if the user hasn't inserted enough money, this method * will throw an Exception instead of returning. */ double buyDrPepper() throws Exception { if (this.numDrPeppers <= 0) { throw new Exception("No more Dr Peppers!"); } if (this.amountInsertedByThisCustomer < 1.25) { throw new Exception("Not enough $$!"); } double change = this.amountInsertedByThisCustomer - 1.25; this.numDrPeppers--; this.amountInsertedByThisCustomer = 0.0; this.amountInSales += 1.25; return change; } /** * Buy a foofy Starbucks beverage, and return the amount of change (in * dollars) owed back to the customer. (Starbucks cost $8.00.) If there are * no more Starbucks in the machine, or if the user hasn't inserted enough * money, this method will throw an Exception instead of returning. */ double buyStarbucks() throws Exception { if (this.numStarbucks <= 0) { throw new Exception("No more Starbucks!"); } if (this.amountInsertedByThisCustomer < 8.00) { throw new Exception("Not enough $$!"); } double change = this.amountInsertedByThisCustomer - 8.00; this.numStarbucks--; this.amountInsertedByThisCustomer = 0.0; this.amountInSales += 8; return change; } /** * The vending machine man comes to refill this machine, setting it back to * the contents of an ordinary newly-installed machine, and collecting all * the big bucks it racked up from customers (in its return value). */ double refill() { this.numDrPeppers = 8; this.numStarbucks = 6; this.amountInsertedByThisCustomer = 0; double amt = this.amountInSales; this.amountInSales = 0; return amt; } }