⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 shoppingcart.java

📁 学JAVA时
💻 JAVA
字号:
package com.zhang.struts.util;

import java.util.*;

import com.zhang.struts.po.Book;



public class ShoppingCart {
	  HashMap items = null;//用来存放多个 ShoppingCartItem
	  int numberOfItems = 0;//ShoppingCartItem的个数

	  //构造 得到一个空HashMap 相当于一个购物车
	  public ShoppingCart() {
	      items = new HashMap();
	  }

	  //增加
	  public synchronized void add(String bookId, Book book) {
	    
		  //如果有此bookId则返回true
		  if(items.containsKey(bookId)) {
			  //从HashMap中取出 并调用增加数量方法
	        ShoppingCartItem scitem = (ShoppingCartItem) items.get(bookId);
	        scitem.incrementQuantity();
	    } else {
	    	//如果没有 新建一个ShoppingCartItem
	        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--;
	    }
	  }

	  //得到HashMap中的 所有ShoppingCartItem
	  public synchronized Collection getItems() {
	      return items.values();
	  }

	  
	  //清空购物车
	  protected void finalize() throws Throwable {
	      items.clear();
	  }

	  //得到HashMap中的 ShoppingCartItem的数量
	  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();
	        Book book = (Book) item.getItem();

	        amount += item.getQuantity() * book.getNowPrice().doubleValue();
	       
	    }
	    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;
	  }
	}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -