1. 程式人生 > >Java簡單購物車Cart

Java簡單購物車Cart

B:

package com.lijiaxing.List;

import org.junit.Test;

import java.util.Iterator;
import java.util.List;

public class B {
    private List<Goods> list;
    public B(){
        Cart cart = new Cart();
        list = cart.getList();
    }
    public List buy(Goods newGoods){
        boolean flag = false;
        Iterator<Goods> iterator = list.iterator();//遍歷器
        while (iterator.hasNext()){//是否有下一個
            Goods oldGoods = iterator.next();//得到所有老商品的資訊
            if (newGoods.getNo().equals(oldGoods.getNo())){//判斷新老商品是不是同一種商品
                oldGoods.setShuliang(newGoods.getShuliang()+oldGoods.getShuliang());//老商品數量+新商品數量
                flag = true;
                break;
            }
        }
        if (!flag){//新商品
            list.add(newGoods);//加入新商品
        }
        return list;
    }
    @Test
    public void test(){
        Goods goods1 = new Goods("咖啡","0001",100,2);
        this.buy(goods1);
        Goods goods2 = new Goods("咖啡","0001",100,5);
        this.buy(goods2);
        Goods goods3 = new Goods("牛奶","0002",200,1);
        this.buy(goods3);
        Goods goods4 = new Goods("方糖","0003",50,20);
        this.buy(goods4);
        Goods goods5 = new Goods("方糖","0003",50,10);
        this.buy(goods5);
        Goods goods6 = new Goods("奶茶","0004",150,50);
        List<Goods> list = this.buy(goods6);
        for (Goods goods :list){
            System.out.println(goods.getName()+":"+goods.getShuliang()*goods.getPrice());
        }
    }
}

Cart:

package com.lijiaxing.List;

import java.util.ArrayList;
import java.util.List;

public class Cart {
    private List<Goods> list = new ArrayList<>();

    public List<Goods> getList() {
        return list;
    }

    public void setList(List<Goods> list) {
        this.list = list;
    }
}

Goods:

package com.lijiaxing.List;

public class Goods {
    private String name;
    private String no;
    private float price;
    private int shuliang;

    public Goods(){

    }
    public Goods(String name, String no, float price, int shuliang) {
        this.name = name;
        this.no = no;
        this.price = price;
        this.shuliang = shuliang;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getNo() {
        return no;
    }

    public void setNo(String no) {
        this.no = no;
    }

    public float getPrice() {
        return price;
    }

    public void setPrice(float price) {
        this.price = price;
    }

    public int getShuliang() {
        return shuliang;
    }

    public void setShuliang(int shuliang) {
        this.shuliang = shuliang;
    }
}