计算arrayList java中对象的权重

时间:2013-10-31 13:10:19

标签: java arraylist

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

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

1 个答案:

答案 0 :(得分:-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();
}