このアイテムの配列リスト内のアイテムの重量を数えようとしています。しかし、アイテムを正しく追加していませんか? これがなぜなのか誰にもわかりますか?
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();
}