-2

2 つの Java クラスを使用してショッピング カート プロセスを実装しようとしています。1つはカートのすべてのプロセスを保持CartItemするもう1つはです。ShoppingCart

これが私のものCartItemです:

public class CartItem implements Serializable {

    private int pro_id;
    private int qnty;


    public CartItem(int pro_id, int qnty) {
        this.pro_id = pro_id;
        this.qnty = qnty;

    }
    // getters and setters
    ....
        // checking the item is already in the cart or not
        public boolean isSameProduct(CartItem item) {
        return this.pro_id == item.getPro_id();

    }

ShoppingCartのクラス:

public class ShoppingCart {

    private CopyOnWriteArrayList<CartItem> itemList;


    public ShoppingCart() {
        this.itemList = new CopyOnWriteArrayList<CartItem>();

    }
    // adding item something wrong here I think..
    public boolean addItem(CartItem item) {
        boolean flag = false;
        if (!this.itemList.isEmpty()) {
            for (CartItem itm : this.itemList) {
                if (itm.isSameProduct(item)) {
                    itm.setQnty(item.getQnty() + itm.getQnty());
                    flag = true;
                   break;

                } else {
                    this.itemList.add(item);
                    flag = true;
                    break;
                }

            }
        } else {
            this.itemList.add(item);
            flag = true;
        }
        return flag;

    }

    public void removeItem(int item_id) {
        for (CartItem item : this.itemList) {
            if (item.getPro_id() == item_id) {
                this.itemList.remove(item);
            }
        }
    }

製品と出力を追加する方法は次のとおりです。

ShoppingCart sc = new ShoppingCart();
sc.addItem(new CartItem(1, 1));
sc.addItem(new CartItem(1, 2));
sc.addItem(new CartItem(1, 3));
sc.addItem(new CartItem(1, 1));
sc.addItem(new CartItem(2, 1));
sc.addItem(new CartItem(2, 2));
sc.addItem(new CartItem(3, 4));
sc.addItem(new CartItem(3, 1));
 // sc.removeItem(3);

for (CartItem item : sc.itemList) {
    System.out.println("Item id - " + item.getPro_id() + " : Item Qnty - " + item.getQnty());
}

出力:

Item id - 1 : Item Qnty - 7
Item id - 2 : Item Qnty - 1
Item id - 2 : Item Qnty - 2
Item id - 3 : Item Qnty - 4
Item id - 3 : Item Qnty - 1

しかし期待される:

Item id - 1 : Item Qnty - 7
Item id - 2 : Item Qnty - 3
Item id - 3 : Item Qnty - 5

前もって感謝します。

4

1 に答える 1