Shopping Cart Class
Shopping Cart Class
Shopping Cart Class
Introduction To Computing II
Dickinson College
Spring Semester 2003
Grant Braught
import java.util.*;
/**
* This class models the Shopping Cart used in
* the on-line e-commerce system example.
*/
public class ShoppingCart {
/**
* Construct a new ShoppingCart for the customer
* with the specified customerID.
*
* @param the id of the customer for which this
* ShoppingCart is being created.
*/
public ShoppingCart(int customerID) {
this.customerID = customerID;
productList = new ArrayList();
}
/**
* Add the specified Product to this ShoppingCart.
*
* @param p the Product to be added to this ShoppingCart.
*/
public void addProduct(Product p) {
productList.add(p);
}
/**
* Get a string describing the contents of this ShoppingCart.
*
* @return a string describing the contents of this ShoppingCart.
*/
public String getContents() {
String s = "";
// Get the description of each Product in this ShoppingCart
// and append it to the end of a String, producing one long
// string describing all of the Products.
for (int i=0; i<productList.size(); i++) {
Object obj = productList.get(i);
Product p = (Product)obj;
s = s + "\n" + p.toString();
}
return s;
}
/**
* Get the ID of the customer who owns this ShoppingCart.
*
* @param the ID of the customer who owns this ShoppingCart.
*/
public int getCustomerID() {
return customerID;
}
/**
* Get the number of Products contained in this ShoppingCart.
*
* @return the number of Products contained in this ShoppingCart.
*/
public int getItemCount() {
return productList.size();
}
/**
* Get the total price of all of the Products contained
* in this ShoppingCart.
*
* @return the total price of all Products in this
* ShoppingCart.
*/
public double getTotalPrice() {
double totalPrice = 0;
// Get the price of each Product in this ShoppingCart and
// add it to the totalPrice. Notice that polymorphism allows
// this method to work for both Products and DiscountProducts.
for (int i=0; i<productList.size(); i++) {
Object obj = productList.get(i);
Product p = (Product)obj;
totalPrice = totalPrice + p.getPrice();
}
return totalPrice;
}
/**
* Remove the specified product from this ShoppingCart.
*
* @param p the Product to be removed from this ShoppingCart.
*/
public void removeProduct(Product p) {
productList.remove(p);
}
}