我正在尝试计算此项目数组列表中项目的权重。但是它没有正确添加项目?谁能明白为什么会这样?
int totalWeight = 0;
for (Item i : items) {
totalWeight = totalWeight + i.getWeight();
}
return totalWeight;
请提供Item
课程代码。它可能看起来像这样:
public class Item {
public Item(int weight) {
this.weight = weight;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
int weight;
}
用法:
ArrayList<Item> items = new ArrayList<Item>();
// add something here
int totalWeight = 0;
for(Item i: items){
totalWeight = totalWeight + i.getWeight();
}