java - 你们能否检查一下我在 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);
}
}
}
解决方案
您正在尝试在循环时添加产品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);
}
推荐阅读
- node.js - 节点 FastCGI 与 HTTP
- javascript - 如果未使用 js 检查单选按钮,则执行某些操作
- wordpress - WordPress中的碳字段,不要更新图库
- azure-blob-storage - 大型机事务文件 SFTP 到 Azure 文件存储或 Blob
- c# - 总和随着每一轮而变化
- ansible - Ansible:如何创建一个跳过库存文件第一个元素的任务
- reactjs - ReferenceError:提供的未定义
- android - 使用 Firebase 刷新回收站视图后,Android 应用程序返回上一个屏幕
- android - 如何在通过以太网连接到互联网的 Android 系统上以编程方式配置静态 IP 地址、网络掩码、网关?
- c# - 数据库表为空时无法在 SFGrid 中添加行