[英]counting weights of objects in arrayList java
我正在尝试在此项目数组列表中计算项目的权重。 但是,这不是正确地添加项目吗? 谁能看到为什么会这样吗?
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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.