zoukankan      html  css  js  c++  java
  • JSP---网上商城购物车

    购物项CartItem.java

     1 package zyz.shop.cart;
     2 
     3 import zyz.shop.product.Product;
     4 
     5 public class CartItem {
     6     private Product product;//商品(不采用productId,而采用对象以便更好地封装)
     7     private int count;//数量
     8 
     9     public Product getProduct() {
    10         return product;
    11     }
    12 
    13     public void setProduct(Product product) {
    14         this.product = product;
    15     }
    16 
    17     public int getCount() {
    18         return count;
    19     }
    20 
    21     public void setCount(int count) {
    22         this.count = count;
    23     }
    24 }

    购物车Cart.java

     1 package zyz.shop.cart;
     2 
     3 import java.util.ArrayList;
     4 import java.util.Iterator;
     5 import java.util.List;
     6 
     7 public class Cart {
     8     List<CartItem> items = new ArrayList<CartItem>();//所有购物项
     9 
    10     public List<CartItem> getItems() {
    11         return items;
    12     }
    13 
    14     public void setItems(List<CartItem> items) {
    15         this.items = items;
    16     }
    17     //添加购物项ci到购物车
    18     public void  add(CartItem ci) {
    19         Iterator<CartItem> it=items.iterator();
    20         while(it.hasNext()){//如果购物车中有此商品,则该购物项的数量加1
    21             CartItem item=it.next();
    22             if(item.getProduct().getPid()==ci.getProduct().getPid()){
    23                 item.setCount(item.getCount()+1);
    24                 return;
    25             }
    26         }
    27         items.add(ci);//如果没有此商品,则将该购物项添加购物车
    28     }
    29     //计算购物车的总价钱
    30     public double getTotalPrice() {
    31         double s=0.0;
    32         Iterator<CartItem> it=items.iterator();
    33         while(it.hasNext()){
    34             CartItem item=it.next();
    35             s+=item.getProduct().getPrice()*item.getCount();//价格*数量累加
    36         }
    37         return s;
    38     }
    39     //删除指定的购物项
    40     public void deleteCartItemById(int productId) {
    41         Iterator<CartItem> it=items.iterator();
    42         while(it.hasNext()){
    43             CartItem item=it.next();
    44             if(item.getProduct().getPid()==productId){//如果有此商品,则从购物车中移除
    45                 it.remove();
    46             }
    47         }
    48     }
    49 }
  • 相关阅读:
    C++ 日期 & 时间
    C++ 引用
    C++ 指针
    C++ 字符串
    C++ 数组
    C++ 数字
    C++ 函数
    C++ 判断
    C++ 循环
    C++ 运算符
  • 原文地址:https://www.cnblogs.com/beast-king/p/4142090.html
Copyright © 2011-2022 走看看