【发布时间】:2019-03-14 07:07:46
【问题描述】:
大家好,我想复习一下我的 Java 知识,因为我已经有一段时间没有使用 Java 编码了。我正在研究这个包含三个班级的商店项目。 1.Product 2.InventoryItem & 3.Store
Product 类需要一个 String 作为名称,一个 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 类。 我想在构造函数中传递一个新的产品对象作为参数,以便以后更容易将所有信息添加到 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);
}
...
我还想知道,一旦我弄清楚如何将 Object 作为参数传递,我将如何使用 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));
我想弄清楚如何在 Store 类的代码块中传递如上所示的新产品。
【问题讨论】:
-
你得到什么错误?
-
new Product("Bananas", 1.50)20)你是忘了逗号还是这只是复制粘贴错误? -
对不起,我的问题的最后一部分令人困惑。当我说“如上所示”时,我的意思是我如何在上面的代码块中预填充 ArrayList。我想使用该方法来创建新的库存对象。
标签: java object arraylist parameters constructor