购物车的Java代码

2025-01-31 18:02:44
推荐回答(1个)
回答1:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;public class ShoppingCartManager {

HashMap hm=new HashMap();
float totlePrice=0;
//添加book到购物车
public void addBook(String bookId,String bookQuantity){

if(hm.containsKey(bookId)){
int value=Integer.parseInt(hm.get(bookId));
value+=Integer.parseInt(bookQuantity);
hm.put(bookId, value+"");
}else{
hm.put(bookId, bookQuantity);
}
}

//修改数量
public void updateQuantity(String bookId,String bookQuantity){
hm.put(bookId, bookQuantity);
}

//获取购物车的所有信息 并计算总价
public ArrayList getShoppingCart(){
ArrayList al=new ArrayList();
Iterator i=hm.keySet().iterator();
String ids="";
BookTableManager btm=new BookTableManager();
while(i.hasNext()){
ids=ids+","+i.next();
}
al= btm.selectByBookIds(ids);

totlePrice=0; //清空总价,防止无限累计
for(int j=0;j BookBean bb=al.get(j);
totlePrice+=bb.getPrice()*Integer.parseInt(getQuantityById(bb.getBookId()+""));
}

return al;
}

//获取总价
public float getTotlePrice(){
return totlePrice;
}

//根据ID获取数量
public String getQuantityById(String id){
String quantity=hm.get(id);
return quantity;
}

//清空购物车
public void clear(){
hm.clear();
}

//删除购物车中的一本书
public void deleteById(String id){
hm.remove(id);
}
}