我正在为我的作业构建一个Java程序,必须将产品添加到特定商店。尝试从Store类添加到ArrayList时遇到麻烦。
我的类产品如下:
class Product {
private String pName;
private int pPrice;
private int pQty;
public Product (String pName, int pPrice, int pQty) {
this.pName = pName;
this.pPrice = pPrice;
this.pQty = pQty;
}
}
和类存储如下:
class Store {
private String storeName;
ArrayList<Product> pList =new ArrayList<>();
public Store() {
String name = storeName;
pList = new ArrayList<Product>();
}
public Store(String newStoreName,ArrayList<Product> newPList) {
this.storeName = newStoreName;
this.pList = newPList;
}
void setName(String storeName) {
this.storeName = storeName;
}
void setProduct(Product pList) {
pList.add(this.pList);//This return method add undefined for type Product, how to solve this error?
}
String getName() {
return storeName;
}
ArrayList<Product> getProductList() {
return pList;
}
}
答案 0 :(得分:1)
void setProduct(Product pList) {
pList.add(this.pList);//This return method add undefined for type Product, how to solve this error?
}
应该是
void addProduct(Product product) {
pList.add(product);
}
答案 1 :(得分:0)
1-您应该像下面那样更改构造函数:_-
public Store(String newStoreName,ArrayList<Product> newPList) {
this.storeName = newStoreName;
pList.addAll(newPList);// This is standard and recommended way to add all element in list.
}
2-更改您的setProduct方法。该运算符不能像这样工作。
void setProduct(Product pList) {
pList.add(pList);
}