編輯:暫時失去了我的大腦。道歉。在java中添加實例變量的值
如果我有一個名爲numThings的實例變量(每個框中的事物數)的n個Box對象。每個盒子中的numThings是隨機的。我如何計算每個盒子中的所有數字並將它們加在一起?
public class Box {
int numThings = RandomHelper.nextIntFromTo(0, 10);
class Box (int numThings) {
this.numThings = numThings;
}
//set and get numThings code here
List<Box> fullBoxes = new ArrayList<Box>();
if (this.numThings > 0) {
fullBoxes.add(this);
}
//Not sure where to go with this. I want to know the total number of things in all the boxes combined
public void countNumThings() {
for (Box box: fullBoxes){
box.getNumThings()
}
}
}
創建一個名爲總和變量,然後加getNumThings()在循環中。謝謝, – csmckelvey 2015-03-03 01:16:20