gpt4 book ai didi

java - 找不到类的方法?

转载 作者:行者123 更新时间:2023-12-01 18:36:02 24 4
gpt4 key购买 nike

我有这个问题:

我必须创建三个类:GroceryList、GroceryItemOrder 和主类 GroceryMain。在我的 GroceryList 类中,弹出此错误:找不到符号 - 方法 add(GroceryItemOrder)。错误位于 GroceryList 类中的 list.add(item) 处。我的类(class)出了什么问题?谢谢。

这是杂货 list :

    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);
}
}

最佳答案

方法add不适用于传统数组。它适用于Arraylist

private GroceryItemOrder[] list;  // Standard Arrays

更改为

private ArrayList<GroceryItemOrder> list;  

现在您可以使用 list.add(element) 添加。

关于java - 找不到类的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21965286/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com