首页 > 解决方案 > 你们能否检查一下我在 Java 上的 ArrayList 的“for 循环”?没有错误,但我似乎无法将数据放入产品 Arraylist

问题描述

我一直在尝试创建将产品添加到 ArrayList 中的方法,同时检查它是否已经存在。但不知何故,循环不会将产品添加到 ArrayList 中,我不知道为什么。

public class Shop1 {

    private String shopName;
    private ArrayList<Product> products;
    private ArrayList<Customer> customers;
    private ArrayList<Transaction> transactions;

    public Shop1(String shopName)
    {
        this.shopName = shopName;
        products = new ArrayList<Product>();
        customers = new ArrayList<Customer>();
        transactions = new ArrayList<Transaction>();
    }

    //addProduct
    public void addProduct(String product_id,String product_name,int product_price,int product_amnt)
    {
        for(Product p:products)
        {
            if(p.getproduct_name().equals(product_name)) 
            {
                int amnt;
                amnt = p.getproduct_stockamnt()+product_amnt;
                p.setproduct_stockamnt(amnt);
            }
            else 
            {
                Product pr = new Product(product_id,product_name,product_price,product_amnt);
                products.add(pr);
            }
        }
    }

标签: javafor-loopif-statementarraylist

解决方案


您正在尝试在循环时添加产品products。所以如果products是空的,什么都不会发生。

您想完全循环浏览产品,然后可能会添加产品。

像这样的东西,例如:

public void addProduct(String product_id, String product_name, int product_price, int product_amnt)
{
    for (Product p: products)
    {
        if (p.getproduct_name().equals(product_name)) 
        {
            int amnt = p.getproduct_stockamnt() + product_amnt;
            p.setproduct_stockamnt(amnt);
            return; // found so no need to go any further
        }
    }
    // We did not find it, so add a new product:
    Product pr = new Product(product_id,product_name,product_price,product_amnt);
    products.add(pr);
}

推荐阅读