日期:2014-05-20 浏览次数:20638 次
package com.ssj.test; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; public class Shopping { private ShopCar shopCar ; public Shopping() { shopCar = new ShopCar(); } public void add(String id , int num) { shopCar.add(id, num); } public void alter(String id , int num){ shopCar.alter(id, num); } public void del(String id){ shopCar.del(id); } /** * 结算 */ public void slmt(){ int spend = 0; Set<Entry<String, Integer>> entrys = shopCar.map.entrySet(); for (Entry<String, Integer> entry : entrys) { int num = entry.getValue(); int price = Commodity.getPrice(entry.getKey()); spend+=num*price; System.out.println("商品["+entry.getKey()+"],数量["+num+"],单价["+price+"],小计["+num*price+"]"); } System.out.println("结算总共消费"+spend+"元"); shopCar.map.clear(); } class ShopCar{ Map<String, Integer> map = new HashMap<String, Integer>(); public void add(String id , int num){ if(map.get(id)==null) map.put(id, num); else map.put(id, map.get(id)+num); System.out.println("增加购物车中商品["+id+"]数量为["+map.get(id)+"]"); } public void alter(String id , int num){ map.put(id, num); System.out.println("修改购物车中商品["+id+"]数量为["+num+"]"); } public void del(String id ) { map.remove(id); System.out.println("删除购物车中商品["+id+"]"); } } static final class Commodity{ public static final Map<String,Integer> map = new HashMap<String,Integer>(); static{ map.put("PAPER", 80) ; map.put("THOOTHBRUSH", 120) ; map.put("WATER", 300) ; } public static int getPrice(String id){ return map.get(id); } } public static void main(String[] args) { Shopping shopper = new Shopping(); //买5个纸团 shopper.add("PAPER", 5); //买2个牙刷 shopper.add("THOOTHBRUSH", 2); //买2桶水 shopper.add("WATER",2); //水买少了,再买10桶 shopper.add("WATER",1); //算了点的手疼,直接把水改成12桶吧 shopper.alter("WATER", 12); //牙刷昨天买了……删了吧 shopper.del("THOOTHBRUSH"); //做结算 shopper.slmt(); } }