简体   繁体   中英

How do I print every object in an arraylist and correctly count their quantity?

I have a class which takes an arraylist of items determined by their name, price and quantity and is supposed to print each unique item and increase quantity accordingly if more than one of the same item are added to the arraylist.

I have 2 problems with my current code: Firstly, It only prints the last item in the arraylist. Secondly, it returns an incorrect quantity for the printed item.

package shop;

import java.text.DecimalFormat;
import java.util.ArrayList;

public class ShoppingCart {
static ArrayList<Product> cart;

    public ShoppingCart() {
        ShoppingCart.cart = new ArrayList<Product>();
    }

    @Override
    public String toString() {
        DecimalFormat format = new DecimalFormat ("#.00");
        int quantity = 0;
        double price = 0;
        String name = null;
        double total = 0;
        for (Product p: cart) {
            quantity = p.getQuantity();
            price = p.getPrice();
            name = p.getName();
            total = p.getTotalPrice();  
        }
        return quantity + " * GBP    " + format.format(price) + " " + name            + "    = GBP   " + format.format(total);  
    }
    public void add(Product p) {
            if(cart.size() > 0) {
                for (int i = 0; i < cart.size(); i++) {
                    if(cart.get(i).getName().equals(p.getName()) 
                    && cart.get(i).getPrice() == p.getPrice()) {

                        cart.get(i).setQuantity(cart.get(i).getQuantity() + p.getQuantity());

                    }else {
                        cart.add(p);
                    }
                }
            }else {
            cart.add(p);
        }
    }   

    public static void main(String[] args) {
        ShoppingCart newCart = new ShoppingCart();

        Product apple, apples, milk, caulk, ice, snakes;
        apple = new Product("Apples (4 pack)", 1.20, 1);
        apples = new Product("Apples (4 pack)", 1.20, 2);
        milk = new Product("Milk (1l)", 0.75, 1);
        caulk = new Product("Caulk (1l)", 6.84, 1);
        ice = new Product("Ice (1kg)", 4.30, 1);
        snakes = new Product("Snake (5m)", 32.0, 1);

        newCart.add(apple);
        newCart.add(apple);
        newCart.add(apple);
        newCart.add(apple);
        newCart.add(caulk);
        newCart.add(milk);


        System.out.println(newCart);


    }
}

The output is

4 * GBP    .75 Milk (1l)    = GBP   3.00

I'm guessing something has gone wrong in my toString() and add() methods, but I can't tell what.

  1. You need to implement Product.toString() as follow for example :

     @Override public String toString() { DecimalFormat format = new DecimalFormat("#.00"); return String.format("%d * GBP %5s %15s= GBP %5s", quantity, format.format(price), name, format.format(price * quantity)); }
  2. And the ShoppingCart.toString() will use Product.toString() of each Product :

     @Override public String toString() { double total = 0; StringBuilder sb = new StringBuilder(); for (Product p : cart) { sb.append(p.toString()).append("\\n"); total += p.getTotalPrice(); } sb.append(String.format("%s%33.2f", "Total :", total)); return sb.toString(); }
  3. Finally you'll get :

     8 * GBP 1,20 Apples (4 pack)= GBP 9,60 2 * GBP 6,84 Caulk (1l)= GBP 13,68 4 * GBP ,75 Milk (1l)= GBP 3,00 4 * GBP ,75 Milk (1l)= GBP 3,00 Total : 29,28

As now, when you set a new quantity it affects the initial object as it's referenced in the list, you need to add a copy of in the list, also change the loop : when you find the same product, change the quantity then return, and **only at the end of the loop* if you haven't find the product you'll add it, you need to wait to check all the existant products :

public void add(Product p) {
    if (cart.size() > 0) {
        for (Product product : cart) {
            if (product.getName().equals(p.getName()) && product.getPrice() == p.getPrice()) {
                product.setQuantity(product.getQuantity() + p.getQuantity());
                return;
            }
        }
        cart.add(new Product(p));
    } else {
        cart.add(new Product(p));
    }
}

And in Product class, a copy constructor :

public Product(Product p) {
    this.quantity = p.quantity;
    this.price = p.price;
    this.name = p.name;
}

Also, don't make the list static, each shoppingCart has its own list

private ArrayList<Product> cart;

public ShoppingCart() {
    cart = new ArrayList<>();
}

In toString() method you have a for loop but you are just keeping last item data in the loop. you should correct it like this:

   String name = "";
   for (Product p: cart) {
        quantity += p.getQuantity();
        price += p.getPrice();
        name += p.getName();
        total += p.getTotalPrice();  
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM