我有这个问题:
我必须创建三个类,GroceryList,GroceryItemOrder和GroceryMain,即主类。在我的GroceryList类中,弹出此错误:找不到符号 - 方法添加(GroceryItemOrder)。错误发生在GroceryList类的list.add(item)中。我的课有什么问题?感谢。
这是GroceryList:
import java.util.*;
public class GroceryList {
private GroceryItemOrder[] list;
int num;
public GroceryList() {
list = new GroceryItemOrder[10];
this.num = 0;
}
public void add(GroceryItemOrder item) {
list.add(item);
}
public double getTotalCost() {
double totalcost = 0;
for(int i = 0; i < list.length; i++){
totalcost += getGroceryItemOrder(getCost());
}
return totalcost;
}
}
这是GroceryItemOrder:
public class GroceryItemOrder {
private String name;
private double pricePerUnit;
private int quantity;
public GroceryItemOrder(String name, int quantity, 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 GroceryMain {
public static void main(String[] args) {
GroceryList list = new GroceryList();
GroceryItemOrder chips = new GroceryItemOrder("chips", 5, 1.25);
list.add(chips);
GroceryItemOrder apples = new GroceryItemOrder("apples", 4, 0.50);
list.add(apples);
GroceryItemOrder oranges = new GroceryItemOrder("oranges", 1, 1.00);
list.add(oranges);
GroceryItemOrder blueberries = new GroceryItemOrder("blueberries", 10, .05);
list.add(blueberries);
GroceryItemOrder strawberries = new GroceryItemOrder("strawberries", 1, 4.00);
list.add(strawberries);
GroceryItemOrder cheese = new GroceryItemOrder("cheese", 1, 3.00);
list.add(cheese);
GroceryItemOrder chocolate = new GroceryItemOrder("chocolate", 1, 1.50);
list.add(chocolate);
GroceryItemOrder milk = new GroceryItemOrder("milk", 2, 3.00);
list.add(milk);
GroceryItemOrder yogurt = new GroceryItemOrder("yogurt", 3, 1.00);
list.add(yogurt);
GroceryItemOrder tacos = new GroceryItemOrder("tacos", 1, 2.50);
list.add(tacos);
}
}
答案 0 :(得分:4)
方法add
不适用于传统阵列。它适用于Arraylist
。
private GroceryItemOrder[] list; // Standard Arrays
将其更改为
private ArrayList<GroceryItemOrder> list;
现在您可以使用list.add(element)
添加。