1. 程式人生 > >用Java Map相關知識實現簡易購物車功能

用Java Map相關知識實現簡易購物車功能

實現購物車功能

問題:實現一個購物車功能
分析:要實現這個功能,可以建立三個類,分別是Product商品類,ShopCart購物車類,Exercise測試類。Product類,裡面描述商品的一些基本屬性,編號,名稱,單價。

下面演示如何用程式碼實現需求。先定義一個商品類。

package com.mycode.set.exercise;

import java.math.BigDecimal;

/**
 *商品類 
 *
 */
public class Product {
	//商品編號
   private int id;
   //商品名稱
   private String name;
   //單價
   private BigDecimal price;
public int getId() {
	return id;
}
public void setId(int id) {
	this.id = id;
}
public String getName() {
	return name;
}
public void setName(String name) {
	this.name = name;
}
public BigDecimal getPrice() {
	return price;
}
public void setPrice(BigDecimal price) {
	this.price = price;
}
@Override
public String toString() {
	return "商品 [id=" + id + ", name=" + name + ", price=" + price + "]";
}
public Product() {
	super();
}

public Product(int id, String name, BigDecimal price) {
	super();
	this.id = id;
	this.name = name;
	this.price = price;
}
@Override
public int hashCode() {
	final int prime = 31;
	int result = 1;
	result = prime * result + id;
	result = prime * result + ((name == null) ? 0 : name.hashCode());
	result = prime * result + ((price == null) ? 0 : price.hashCode());
	return result;
}
@Override
public boolean equals(Object obj) {
	if (this == obj)
		return true;
	if (obj == null)
		return false;
	if (getClass() != obj.getClass())
		return false;
	Product other = (Product) obj;
	if (id != other.id)
		return false;
	if (name == null) {
		if (other.name != null)
			return false;
	} else if (!name.equals(other.name))
		return false;
	if (price == null) {
		if (other.price != null)
			return false;
	} else if (!price.equals(other.price))
		return false;
	return true;
}


}

接下來是Shopcar類。

package com.mycode.set.exercise;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * 購物車類
 *
 */
public class ShopCar {
	 //用來存放商品資訊和數量
     Map<Product,Integer>  productMap;
     BigDecimal totalPrice=BigDecimal.valueOf(0.0);
     
	  public ShopCar(){
		  
		  productMap=new HashMap<>();
	  }
	  //向購物車中新增商品和數量
	  public void add(Product product,int num){
		  //判斷map中是否包含當前商品,如果不包含,則直接將商品和數量新增到Map裡面
		  if(!productMap.containsKey(product)){
			  
			  productMap.put(product, num);
		  }
		  else{
			  
			  //如果程式走到這裡,說明之前已經向購物車中新增過當前商品,需要將數量進行相加運算
			  int before=productMap.get(product);//取得之前購物車中的商品數量
			  int after=before+num;
			  productMap.put(product, after);
		  }
		  //總價=商品單價*數量
		
		  totalPrice=totalPrice.add(product.getPrice().multiply(BigDecimal.valueOf(num)));
	  }
	  
	  //從購物車中刪除商品和數量
	  public void remove(Product product,int num){
		  //獲取購物車中的商品數量
		  int before=productMap.get(product);
		  //將該商品從購物車中刪除
		  if(num>=before){
			  
			  productMap.remove(product);
			  totalPrice=totalPrice.subtract(product.getPrice().multiply(BigDecimal.valueOf(num)));
			  
		  }
		  else{
			  //剩餘的商品數量
			    int after=before-num;
			    productMap.put(product, after);
			  
		  }
		  totalPrice.subtract(product.getPrice().multiply(BigDecimal.valueOf(num)));
	  }
	  //清空購物車
	  public void clear(){
		  
		  productMap.clear();
		  totalPrice=totalPrice=BigDecimal.valueOf(0.0);
	  }
	  //列印詳單
	  public void print(){
		   System.out.println("商品清單:"); 
		   //獲取map中所有的鍵
		    Set<Product> key=productMap.keySet();
		    Iterator<Product> iter=key.iterator();
		    while(iter.hasNext()){
		    	
		    	Product p=iter.next();
		    	Integer i=productMap.get(p);
		    	System.out.println(i+ "件    "+p+"\t\t\t"+p.getPrice().multiply(BigDecimal.valueOf(i)));
		    	
		    }
		    System.out.println("\t\t\t\t\t總價:"+totalPrice);
	  }
	  
}

最後是測試類,測試相關功能

package com.mycode.set.exercise;

import java.math.BigDecimal;

/**
 * 
 *分析:要實現這個功能,可以建立三個類,分別是Product商品類,ShopCart購物車類,Exercise測試類。
        Product類,裡面描述商品的一些基本屬性,編號,名稱,單價
 */
public class Exercise06 {
    public static void main(String[] args) {
    	  Product orange=new Product(1001,"橘子",BigDecimal.valueOf(10));
          Product apple=new Product(1002,"蘋果",BigDecimal.valueOf(15));
          Product grape=new Product(1003,"葡萄",BigDecimal.valueOf(20));
          
          ShopCar sc=new ShopCar();
          sc.add(apple, 5);
          sc.add(orange, 10);
          sc.add(grape, 20);
          sc.add(apple, 5);
          //sc.remove(apple, 3);
          //sc.clear();
          sc.print();
	}
}

實現結果如下,這裡的刪除和清楚功能我就不一一測試了,有興趣大家可以試一下。

入門練手小例子,寫的不好,還望大家多多指教。