Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

(10 marks) Consider a simple vending machine class. The machine accepts tokens a

ID: 3573378 • Letter: #

Question

(10 marks) Consider a simple vending machine class. The machine accepts tokens and dispenses cans of refreshing beverages. Write a complete class (on the next page) as described below: The class has two instance data fields; one to keep track of the number of cans in the machine and one to keep track of the number of tokens (think coins) collected. There should be two constructors. One takes no arguments and starts with 50 cans and zero tokens. The other takes one argument, the initial number of cans in the machine. There should be a method to purchase a drink which adds one token to the machine and subtracts one can – assuming there are still cans in the machine to be purchased. There should be one method to add cans to the machine. There should be separate methods to return the number of cans remaining and the number of tokens collected. Bonus (+2 marks): Write a toString( ) method to allow for easy printing of a vending machine object. For any other assumptions you are making, use comments. Don’t write Java Docs

Explanation / Answer

public class VendingMachine {

   // Instance variables
   private int cans;
   private int tokens;

   // No arguments constructor
   public VendingMachine() {
       this.cans = 50;
       this.tokens = 0;
   }

   // Parameterized constructor
   public VendingMachine(int initialCans) {
       this.cans = initialCans;
       this.tokens = 0;
   }
  
   // Purchases a drink from the machine
   // If the number of cans is greater than 0
   // Adds a token and subtracts one can and returns true
   public void purchase() {
       if (this.cans > 0) {
           this.cans -= 1;
           this.tokens += 1;
       }
   }
  
   // Adds n cans to the Vending machine
   public void addCans(int n) {
       this.cans += n;
   }

   // Returns the number of cans remaining
   public int getCans() {
       return cans;
   }

   // Returns the number of tokens collected
   public int getTokens() {
       return tokens;
   }

   // Prints the vending machine object
   @Override
   public String toString() {
       return "Number of cans: " + getCans() + " Number of tokens: " + getTokens();
   }
}