ShoppingCartItem.java表示购物车种每一个物品,物品的详细情况BookDetails,以及数量quantity。package mypack;
public class ShoppingCartItem
{
BookDetails item;
int quantity;

public ShoppingCartItem(BookDetails anItem)
{
item=anItem;
quantity=0;
}

public void incrementQuantity()
{
quantity++;
}

public void decrementQuantity()
{
quantity--;
}

public BookDetails getItem()
{
return item;
}

public int getQuantity()
{
return quantity;
}

}

解决方案 »

  1.   

    ShoppingCart.java表示购物车,每个购物车中包含有若干个购物条目ShoppingCartItem。package mypack;
    import java.util.*;public class ShoppingCart {
      HashMap items = null;
      int numberOfItems = 0;  public ShoppingCart() {
          items = new HashMap();
      }  public synchronized void add(String bookId, BookDetails book) {
        if(items.containsKey(bookId)) {
            ShoppingCartItem scitem = (ShoppingCartItem) items.get(bookId);
            scitem.incrementQuantity();
        } else {
            ShoppingCartItem newItem = new ShoppingCartItem(book);
            items.put(bookId, newItem);
        }    numberOfItems++;
      }  public synchronized void remove(String bookId) {
        if(items.containsKey(bookId)) {
            ShoppingCartItem scitem = (ShoppingCartItem) items.get(bookId);
            scitem.decrementQuantity();        if(scitem.getQuantity() <= 0)
                items.remove(bookId);        numberOfItems--;
        }
      }  public synchronized Collection getItems() {
          return items.values();
      }  protected void finalize() throws Throwable {
          items.clear();
      }  public synchronized int getNumberOfItems() {
          return numberOfItems;
      }
      public synchronized double getTotal() {
        double amount = 0.0;    for(Iterator i = getItems().iterator(); i.hasNext(); ) {
            ShoppingCartItem item = (ShoppingCartItem) i.next();
            BookDetails bookDetails = (BookDetails) item.getItem();        amount += item.getQuantity() * bookDetails.getPrice();
        }
        return roundOff(amount);
      }  private double roundOff(double x) {
          long val = Math.round(x*100); // cents
          return val/100.0;
      }  public synchronized void clear() {
          items.clear();
          numberOfItems = 0;
      }
    }