0

我正在尝试计算此项目数组列表中项目的权重。但是它没有正确添加项目?谁能明白为什么会这样?

int totalWeight = 0;
for (Item i : items) {
    totalWeight = totalWeight + i.getWeight();
}
return totalWeight;
4

1 回答 1

-1

请提供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();
}
于 2013-10-31T13:19:14.963 回答