-2

So i am working on a project for myself where I am learning to make a small webshop using java spark velocity and mongodb, now I am at the point where I can add and remove items in the shoppingcart but for some reason if I add 2 of the same titles(sku in this case) it should just get the amount and do it +1, can any1 tell me where I am going wrong?

for (int i = 0 ; i < list.size(); i++){
        if (Objects.equals(list.get(i).getSku(), sku)){
            Integer newamount = list.get(i).getAmount() + 1;
            newList.append("sku", list.get(i).getSku());
            newList.append("price", list.get(i).getPrice());
            newList.append("amount", newamount);
            DBObject dbObject = new BasicDBObject("shopping_cart", newList);
            coll.update(new BasicDBObject("email", email), new BasicDBObject("$push", dbObject));
zero323
  • 322,348
  • 103
  • 959
  • 935

1 Answers1

0

You are stepping through the entire list array, and find your sku twice.

Instead, you probably want to break out of the FOR loop when you find the sku the first time. So, end your IF bracket with a break; statement.

HTH, Jim

Jim
  • 201
  • 1
  • 8