好的,所以我试图将 arraylist 中对象的权重相加,我遇到了这段代码的问题。该程序给我错误调用“不兼容的类型:对象无法转换为项目”我试图找到解决方案但找不到任何有用的东西。也是的,该项目正在从 .getWeight 返回一个 int
int totalWeight = 0;
if (!(items.isEmpty())){
for (Item i: items){
totalWeight += i.getWeight();
}
return totalWeight;
}
return 0;
让我提供整个代码以供进一步调查。
导入 java.util.ArrayList;
public class Packet {
private ArrayList items;
public Packet(){
ArrayList<Item> items = new ArrayList<>();
}
public void addItem(Item item){
items.add(item);
}
public int totalWeight(){
int totalW = 0;
if (!(items.isEmpty())){
for (Item i: items){
totalW += i.getPaino();
}
return totalW;
}
return 0;
}
}
编辑:: 项目类
public class Item {
private String name;
private int weight;
public Item(String name, int weight){
this.weight = weight;
this.name = name;
}
public String getName(){
return this.name;
}
public int getWeight(){
return this.weight;
}
@Override
public String toString(){
return this.name + " (" + this.weight + " kg)";
}
}
开心每一天1111
眼眸繁星
喵喵时光机
相关分类