大家好,我正在努力温习我的 Java 知识,因为我已经有一段时间没有用 Java 编写代码了。我正在开发这个具有三类的商店项目。 1.产品 2.库存商品 & 3.商店
产品类需要一个字符串作为名称,一个 double 值作为成本。有用于设置和检索数据的访问器和修改器方法。
public class Product {
//fields
private String productName;
private double cost;
/**
* Contructor
*
* @param productName
* @param cost
*/
public Product(String productName, double cost){
this.productName = productName;
this.cost = cost;
}
...
InventoryItem 类在产品信息旁边添加数量。这将清楚地说明为什么使用 Store 类。 我想在构造函数中传递一个新的 Product 对象作为参数,以便以后更轻松地将所有信息添加到 ArrayList 中。如上所述,我创建了名称、成本和数量的 set 和 get 方法。
public class InventoryItem {
//fields
private Product productObject;
private int quantity;
/**
* Constructor
*
* @param quantity
*/
public InventoryItem(new Product, int quantity) {
this.quantity = quantity;
}
/**
* Method to set new name for product in inventory
*
* @param newProductName
*/
public void setProductName(String newProductName) {
productObject.setProductName(newProductName);
}
...
我还想知道一旦我弄清楚如何将对象作为参数传递,我将如何使用 Products 方法。
当尝试使用 InventotyItems 预先填充我的 ArrayList 时,我开始收到错误。这是在我的 Store 类中完成的。
import java.util.ArrayList;
public class Store {
//fields
private String storeName;
private String location;
private ArrayList<InventoryItem> itemList;
/**
* Constructor
*/
public Store(String storeName, String location){
this.storeName = storeName;
this.location = location;
itemList = new ArrayList<>();
}
/**
* Method to prepopulate a list of items the store will be selling
*/
private void setItemList(){
itemList.add(new InventoryItem(new Product("Bananas", 1.50)20));
itemList.add(new InventoryItem(new Product("Canned Beans", 2.00)15));
itemList.add(new InventoryItem(new Product("Easy-Mac", 2.50)15));
itemList.add(new InventoryItem(new Product("Oranges", .50)25));
itemList.add(new InventoryItem(new Product("Cereal", 3.00)10):);
itemList.add(new InventoryItem(new Product("Milk", 4.00)10));
}
}
而不是更改 InventoryItem 中的参数
itemList.add(newInventoryItem("Bananas", 1.50, 20));
我想弄清楚如何传递新的 Product,如上面 Store 类的代码块中所示。
最佳答案
你的语法错误。实例化 InventoryItem
时缺少逗号。
替换
new InventoryItem(new Product("Bananas", 1.50)20)
与
new InventoryItem(new Product("Bananas", 1.50), 20)
关于java - 将一个对象添加到将另一个对象作为参数的 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52722129/