JSP---網上商城購物車

來源:互聯網
上載者:User

標籤:style   blog   ar   color   sp   java   div   art   log   

購物項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()){//如果購物車中有此商品,則該購物項的數量加121             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 }

 

JSP---網上商城購物車

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.