添加totalcost时发生Java错误
求你了,我需要帮助 1-在printOrderCos方法中,我应该打印ArrayList订单中项目的总成本。我定义了可变的totalCost和count。Count的定义使其作为一个索引,遍历order ArrayList的每个elementitem,然后将每个项目的成本相加到totalCost 第二种方法遇到的问题是这行代码:添加totalcost时发生Java错误,java,Java,求你了,我需要帮助 1-在printOrderCos方法中,我应该打印ArrayList订单中项目的总成本。我定义了可变的totalCost和count。Count的定义使其作为一个索引,遍历order ArrayList的每个elementitem,然后将每个项目的成本相加到totalCost 第二种方法遇到的问题是这行代码: totalCost+=order.get(count); 它给出了一个错误: error: The operator += is undefined for the
totalCost+=order.get(count);
它给出了一个错误:
error: The operator += is undefined for the argument type(s) double, Item
代码:
正如错误所说。。order是一个ArrayList,其中包含Item类型的对象:
按原样,您正在尝试向double中添加一项。您可能希望通过执行类似doubleorder.getcount的操作将项目强制转换为double
编辑:评论是对的-我误解了这里的内容。您需要向Item添加一个返回double的方法,然后使用该方法。您正在尝试向double添加Item对象。也许你想要像这样的东西
totalCost+=order.get(count).getValue;
您必须在Item类中创建一个返回此项目成本的方法
public class Item{
private double cost;
...
public double getCost(){
return this.cost;
}
}
然后可以对每个项目调用de getCost,如下所示:
totalCost+=order.get(count).getCost();
因为您没有提供Item类的详细信息,所以我只能假设它是什么样子。根据台词
order.add(new Muffin("Bran", 3));
order.add(new Coffee("Latte", 1));
order.add(new TimBits("Assorted", 24));
...
我假设Item类有一个构造函数,如
public Item(String type, int price) {
this.type = type;
this.price = price;
}
当您使用order.getcount从arraylist获取项对象时,您将获取类型为Item的对象。不能将其添加到基元双精度。其他一些答案建议将该项设置为双精度,但我不认为这会起作用,或者即使它起作用,我也不认为这是添加该项的正确方法。Item类应该有一个价格的getter。差不多
public int getPrice() {
return this.price;
}
行totalCost+=order.getcount//内在价值;表明代码中已经存在类似的方法。使用这种方法,您应该能够添加总成本我不完全确定这是否可行。Item是一个具有自己属性的对象,我根据getItem方法中Items的实例化猜测其类型和价格。应该有一个getter方法来返回项目的成本,而不是试图将对象强制转换为double?我看我的答案没有错!请不要删除已回答的问题!
order.add(new Muffin("Bran", 3));
order.add(new Coffee("Latte", 1));
order.add(new TimBits("Assorted", 24));
...
public Item(String type, int price) {
this.type = type;
this.price = price;
}
public int getPrice() {
return this.price;
}