import java.util.ArrayList; /** * Write a description of class Cart here. * * @author (your name) * @version (a version number or a date) */ public class Cart { //instance vars private ArrayList cart; public Cart() { cart = new ArrayList(); } public void addItem( Item i ) throws Exception { if ( i.getQty() < 0 || i.getPrice() < 0.00) throw new Exception("Qty and price must be positive"); //see how many times this item is already in the cart int numMatches = 0; int index = -1; int qty = 0; for (int j=0; j< cart.size(); j++) { if (cart.get(j).getName().equals(i.getName())) { numMatches++; index = j; } } if (numMatches <= 0) cart.add(i); //add item to cart else { //update the quantity qty = cart.get(index).getQty(); qty += i.getQty(); cart.get(index).setQty(qty); } } public double calculateTotal() { double total =0.0; for(int t=0; t< cart.size(); t++) total += (cart.get(t).getQty() * cart.get(t).getPrice()); return total; } public void checkout() { System.out.println("Shopping Cart"); for (Item x : cart) System.out.println(x); System.out.printf("Total: $%.2f\n" , calculateTotal()); } }