I'm trying to implement shopping cart process using two java classes. One is CartItem
and the other one is ShoppingCart
which holds all the process of the cart.
Here is my 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();
}
My ShoppingCart
class:
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);
}
}
}
Here is the way I am adding products and the out-put :
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());
}
Out-put:
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
But Expected :
Item id - 1 : Item Qnty - 7
Item id - 2 : Item Qnty - 3
Item id - 3 : Item Qnty - 5
Thanks in advance.
Once you have a single item in the cart, you never actually check anything after the first item in the cart, because you always break whilst looping through the list elements:
for (CartItem itm : this.itemList) {
if (itm.isSameProduct(item)) {
itm.setQnty(item.getQnty() + itm.getQnty());
flag = true;
break; // It was the same product; break.
} else {
this.itemList.add(item);
flag = true;
break; // It wasn't the same product; break.
}
}
Instead, you need to make use of flag
's value, and only add the item if flag
is false:
public boolean addItem(CartItem item) {
boolean flag = false;
for (CartItem itm : this.itemList) {
if (itm.isSameProduct(item)) {
itm.setQnty(item.getQnty() + itm.getQnty());
flag = true;
break;
}
}
if (!flag) {
this.itemList.add(item);
flag = true;
}
return flag;
}