J2ee 购物车修改 删除操作如何实现

Java code
  
  
import java.util.ArrayList; import java.util.Iterator; // 购物车 public class ShoppingCart { /** * CartItem表示的是商品类 * 保存所有CartItem对象的容器对象,这就相当于显示生活中的购物车 */ private ArrayList < CartItem > cart; // 进超市,我们先推一辆车...选东西去 public ShoppingCart() { cart = new ArrayList < CartItem > (); } /** * 返回包括所有已经购物的商品信息的容器对象.........把购物车推到收营台 * * * @return 当前的items容器对象------学习高手的编码习惯!!! */ public ArrayList < CartItem > getCart() { return cart; } /** * 添加一种商品到购物车中,如果这种商品在购物车中已经存在, 那就修改已有的商品的数量, * 反之,构造一个新的CartItem对象添加到items对象中. * * @param item * 新增的代表这种商品的对象........一样东西走过去买几次 */ public void addCartItem(CartItem item) { CartItem oldItem = null ; if (item != null ) { for ( int i = 0 ; i < cart.size(); i ++ ) { oldItem = cart.get(i); if (oldItem.getId().equals(item.getId())) { oldItem.setQuantity(oldItem.getQuantity() + item.getQuantity()); return ; } } cart.add(item); } } /** * 从购物车中删除商品........不要的东西可以从购物车中拿出来 * * @param id * 所删除商品的商品编号 * @return 删除成功,返回true,反之返回false */ public void removeCartItem(String id) { CartItem item = null ; for ( int i = 0 ; i < cart.size(); i ++ ) { item = cart.get(i); if (item.getId().equals(id)) { cart.remove(i); return ; } } } /** * 计算所购商品的总价 * * @return 商品的总价........就是我们在超市买完东西应该付的钱 */ public double getTotal() { Iterator < CartItem > it = cart.iterator(); double sum = 0.0 ; CartItem item = null ; while (it.hasNext()) { item = it.next(); sum = sum + item.getSum(); // 各种商品小计之和 } return sum; } /** * 当修改商品的数量的时候,执行该方法 */ public void updateCartItem(String id, int quantity) { CartItem oldItem = null ; if (id != null ) { for ( int i = 0 ; i < cart.size(); i ++ ) { oldItem = cart.get(i); if (oldItem.getId().equals(id)) { oldItem.setQuantity(quantity); return ; } } } } }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值