购物车的代码
来源:互联网 发布:php string length 编辑:程序博客网 时间:2024/05/01 21:26
import java.util.HashMap;
import java.util.Iterator;
/*
* 购物车
*/
public class Cart {
/*
* 通过键值对保存OrderGoodsInfo对象的容器对象
*/
private HashMap<Integer, OrderGoodsInfo> cart;
/**
* 构造方法
*/
public Cart() {
cart = new HashMap<Integer,OrderGoodsInfo>();
}
/**
* 返回包含已经订购的商品信息的容器对象(即购物车对象)
* @return
*/
public HashMap<Integer,OrderGoodsInfo> getCart() {
return cart;
}
/**
* 添加一件商品
* @param goods
*/
public void addGoods(GoodsInfo goods) {
this.addGoods(goods,1);
}
/**
* 添加一种商品到购物车中,如果这种商品在购物车存在,
* 那就修改其数量
* 反之则构造一个新的对象,添加其对象中
* @param goods
* @param quantity:数量
*/
public void addGoods(GoodsInfo goods,int quantity) {
if(goods != null) { //当商品不为空的时候
OrderGoodsInfo orderGoods = null;
if(cart.containsKey(goods.getGoodsId())) { //表示当前商品存在
orderGoods = cart.get(Integer.valueOf(goods.getGoodsId()));
orderGoods.setQuantity(orderGoods.getQuantity() + quantity); //将原来的数量设置成现有的数量加上原来的数量
}else{
orderGoods = new OrderGoodsInfo();
orderGoods.setGoodsInfo(goods);
orderGoods.setQuantity(quantity);
cart.put(Integer.valueOf(goods.getGoodsId()), orderGoods);
}
}
}
/**
* 从购物车中移除商品(根据商品的id)
* @param id
* @return
*/
public boolean removeGoods(int id) {
//判断要移除的商品是否存在
if(cart.containsKey(Integer.valueOf(id))) {
cart.remove(Integer.valueOf(id));
return true;
}
return false;
}
/**
* 清空购物车的方法
*/
public void clearCart() {
if(this.cart != null) {
this.cart.clear();
}
}
/**
* 修改商品数量的方法
* @param goodId
* @param quantity
*/
public void updateQuantity(int goodsId,int quantity) {
if(cart.containsKey(goodsId)) {
OrderGoodsInfo orderGoods = cart.get(goodsId);
orderGoods.setQuantity(quantity);
}
}
/**
* 计算购物车中所有商品的价格
* @return
*/
public double getTotalPrice() {
double sum = 0.0; //总价
Iterator<Integer> iter = cart.keySet().iterator();
OrderGoodsInfo orderGoods = null;
//遍历购物车中所有的商品
while(iter.hasNext()) {
orderGoods = cart.get(iter.next());
sum += orderGoods.getSumPrice();
}
return Math.round(sum*100.0)/100.0;
}
}
- 购物车的代码
- 购物车的代码
- 购物车的代码
- 购物车的代码
- 实现购物车的代码
- 购物车的 java 代码实现方法
- ASP.net购物车的代码程序
- ASP.net购物车的代码程序
- MVC中编写的购物车代码
- 购物车的代码收集起来
- 购物车 数量的加减部分代码
- ionis 和angularjs 购物车的代码
- 购物车的逻辑代码与适配器
- 更新购物车代码
- 购物车详细代码
- 购物车代码
- 购物车JSP代码
- 购物车代码
- csdn
- php自学第一天
- js三级分类菜单导航
- 多处转载综合:UBoot配置过程(顶层Makefile)
- 不知所措
- 购物车的代码
- 图书馆管理系统(初级)
- 在nokia 手机上使用录音设备(1)
- 运动会
- 第一篇
- 其实坚持下去真的可以看到奇迹
- 心声
- 安装SQL Server 2000 提示文件挂起错误解决办法
- 部分网站打不开如何处理?