Advertisement
Guest User

ShoppingCart.java

a guest
Feb 20th, 2019
154
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.31 KB | None | 0 0
  1. // **********************************************************************
  2. //   ShoppingCart.java//
  3. //   Represents a shopping cart as an array of items
  4. // **********************************************************************
  5. import java.text.NumberFormat;
  6. public class ShoppingCart {
  7.     private int itemCount;
  8.     private Item[] cart;
  9.     // total number of items in the cart
  10.     private double totalPrice;
  11.     // total price of items in the cart
  12.     private int capacity;
  13.     // current cart capacity
  14.     // -----------------------------------------------------------
  15.     //  Creates an empty shopping cart with a capacity of 5 items.
  16.     // -----------------------------------------------------------
  17.     public ShoppingCart() {
  18.         capacity = 5;
  19.         itemCount = 0;
  20.         totalPrice = 0.0;
  21.         cart = new Item[capacity];
  22.     }
  23.     // -------------------------------------------------------
  24.     //  Adds an item to the shopping cart.
  25.     // -------------------------------------------------------
  26.     public void addToCart(String itemName, double price, int quantity) {
  27.         if (itemCount == cart.length) {
  28.             increaseSize();
  29.         }
  30.         cart[itemCount] = new Item(itemName, price, quantity);
  31.         totalPrice += price * quantity;
  32.         itemCount++;
  33.     }
  34.     // -------------------------------------------------------
  35.     //  Returns the contents of the cart together with
  36.     //  summary information.
  37.     // -------------------------------------------------------
  38.     public String toString() {
  39.         NumberFormat fmt = NumberFormat.getCurrencyInstance();
  40.         String contents = "\nShopping Cart\n";
  41.         contents += "\nItem\t\tUnit Price\tQuantity\tTotal\n";
  42.         for (int i = 0; i < itemCount; i++)
  43.             contents += cart[i].toString() + "\n";
  44.         contents += "\nTotal Price: " + fmt.format(totalPrice);
  45.         contents += "\n";
  46.         return contents;
  47.     }
  48.     // ---------------------------------------------------------
  49.     //  Increases the capacity of the shopping cart by 3
  50.     //---------------------------------------------------------
  51.     private void increaseSize() {
  52.         Item[] temp = new Item[cart.length + 3];
  53.         for (int i = 0; i < cart.length; i++) {
  54.             temp[i] = cart[i];
  55.         }
  56.         cart = temp;
  57.     }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement