cart.java

来自「bs_网上购物系统每个例子文件夹都附有数据库表、程序源文件和一个war包(或者j」· Java 代码 · 共 75 行

JAVA
75
字号
package bo;

import java.util.*;
import vo.Products;

public class Cart extends ArrayList {
    private Double totalPrice;
    public Cart() {
    }

    public void setTotalPrice(Double totalPrice) {
        this.totalPrice = totalPrice;
    }

    /**
     * 添加一个商品到购物车
     * @param product Products
     * @param quantity Integer
     */
    public void addProduct(Products product, Integer quantity) {
        if (quantity == null) {
            quantity = new Integer(1);
        }
        CartItem item = this.getCartItem(product.getProductId());
        if (item != null) {
            item.setQuantity(new Integer(item.getQuantity().intValue() +
                                         quantity.intValue()));
        } else {
            item = new CartItem();
            item.setProduct(product);
            item.setQuantity(quantity);
            this.add(item);
        }
    }
    /**
     * 计算当前购物车所有商品的总金额
     * @return Double
     */
    public Double getTotalPrice() {
        double totalPrice = 0;
        for (int i = 0; i < this.size(); i++) {
            CartItem item = (CartItem)this.get(i);
            totalPrice += item.getQuantity().intValue() *
                    item.getProduct().getPrice().doubleValue();
        }
        return new Double(totalPrice);
    }
    /**
     * 从购物车中删除指定的商品
     * @param product Products
     */
    public void removeProduct(Products product) {
        CartItem item = this.getCartItem(product.getProductId());
        if (item != null) {
            this.remove(item);
        }
    }
    /**
     * 获得指定商品id的购买记录,如果不存在,则返回Null
     * @param productId String
     * @return CartItem
     */
    public CartItem getCartItem(String productId) {
        for (int i = 0; i < this.size(); i++) {
            CartItem item = (CartItem)this.get(i);
            if (item.getProduct().getProductId().equals(productId)) {
                System.out.println("getCartItem ==>" + item.getProduct().getProductId());
                return item;
            }

        }
        return null;
    }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?