/**
 *  A cash register totals up sales and computes change due.
 *    @author  Dave Reed (based on code by Cay Horstmann)
 *    @version 2/2/10
*/
public class CashRegister2 {
   private double purchase;
   private double payment;
   private int numItems;
   
   /**
    * Constructs a cash register with no money in it.
    */
   public CashRegister2() {
      this.purchase = 0;
      this.payment = 0;
      this.numItems = 0;
   }

   /**
    * Records the sale of an item.
    * @param amount the price of the item
    */
   public void recordPurchase(double amount) {
      if (amount > 0) {
          this.purchase = this.purchase + amount;
          this.numItems = this.numItems + 1;
      }
      else {
          System.out.println("ILLEGAL PURCHASE");
      }
   }

   /**
    * Enters the payment received from the customer.
    * @param amount the amount of the payment
    */
   public void enterPayment(double amount) {
      if (amount > 0) {
          this.payment = this.payment + amount;
      }
      else {
          System.out.println("ILLEGAL PAYMENT");
      }
    }

   /**
    * Computes the change due and resets the machine for the next customer.
    * @return the change due to the customer
    */
   public double giveChange() {   
      double change = this.payment - this.purchase;
      
      if (change >= 0) { 
          this.purchase = 0;
          this.payment = 0;
          this.numItems = 0;
          return change;
      }
      else {
          System.out.println("YOU NEED TO ENTER $" + -change);
          return change;
      }
   }
   
   /**
    * Accessor method for the number of items purchased.
    *   @return the number of items purchased so far
    */
   public int numberOfItems() {
       return this.numItems;
   }
   
   /**
    * Computes the average price of all purchases.
    *   @return the average of all purchases made so far
    */
   public double averagePurchase() {
       if (this.numItems > 0) {
           return this.purchase/this.numItems;
       }
       else {
           return 0.0;
       }
   }
}
