使用GroceryList的java建议
我正在制作一个程序,我有一个名为GroceryItem的类,另一个名为GroceryList,第三个是运行程序的main方法
我在这个项目上做了很多,但我现在被卡住了。请看一下我的代码并帮助我
食品杂货类:
public class GroceryItem {
private String name;
private double pricePerUnit;
private int quantity;
public GroceryItem(int quantity, String name, double pricePerUnit) {
this.name = name;
this.pricePerUnit = pricePerUnit;
this.quantity = quantity;
}
public double getCost() {
return (this.quantity * this.pricePerUnit);
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
}
杂货店类别:
public class GroceryList {
private GroceryItem[] list = null;
int num;
public GroceryList() {
list = new GroceryItem[10];
this.num = 0;
}
// Constructs a new empty grocery list.
public void add(GroceryItem item) {
list.add(item);
}
// Adds the given item order to this list, if the list is not full (has
// fewer than 10 items).
public double getTotalCost() {
double totalcost = 0;
for(int i = 0; i < list.length; i++){
totalcost += getGroceryItemOrder(getCost());
}
return totalcost;
}
// Returns the total sum cost of all grocery item orders in this list.
}
主要方法:
public static void main(String[] args) {
GroceryList list = new GroceryList();
GroceryItem carrots = new GroceryItem(5,"Carrots", 0.40);
list.add(carrots);
GroceryItem apples = new GroceryItem( 4,"Apples", 0.15);
list.add(apples);
GroceryItem rice = new GroceryItem( 1,"Rice", 1.10);
list.add(rice);
GroceryItem tortillas = new GroceryItem(10,"Tortillas", .05);
list.add(tortillas);
GroceryItem strawberries = new GroceryItem(1,"Strawberries", 4.99);
list.add(strawberries);
GroceryItem chicken = new GroceryItem( 1,"Chicken", 5.99);
list.add(chicken);
GroceryItem lettuce = new GroceryItem( 1,"Lettuce", 0.99);
list.add(lettuce);
GroceryItem milk = new GroceryItem( 2,"Milk", 2.39);
list.add(milk);
GroceryItem yogurt = new GroceryItem( 3,"Yogurt", 0.60);
list.add(yogurt);
GroceryItem chocolate = new GroceryItem(1,"Chocolate", 3.99);
list.add(chocolate);
}
}
# 1 楼答案
用这个来添加你的购物元素
杂货店类
//在main函数中,可以调用上述指定函数
# 2 楼答案
您正在尝试使用
add
方法向数组中添加内容。 您应该使用ArrayList
或类似的数据结构,或者使用索引添加项:原因是简单数组没有
add
方法ArrayList
和其他几个集合类都可以此外,在原始代码中,您有以下行:
此代码中没有定义方法
getGroceryItemOrder(...)
。在这种形式中,它将在GroceryItemList
类上调用getCost()
GroceryItemList
没有这样的方法,因此会出现错误您想在当前列表项上调用
getCost()
,因此需要的行是: