2015-03-03 40 views
-2

編輯:暫時失去了我的大腦。道歉。在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() 
      } 
    } 


} 
+0

創建一個名爲總和變量,然後加getNumThings()在循環中。謝謝, – csmckelvey 2015-03-03 01:16:20

回答

1

一個簡單的實現可以是:

public int countNumThings() { 
     int totalThings=0; 
     for (Box box: fullBoxes){ 
       totalThings = totalThings+box.getNumThings(); 
     } 
     return totalThings; 
    } 
+0

,暫時失去了我的大腦 – 2015-03-03 01:24:03

1

你必須做這樣的事情:

public int countNumFromBoxes(List<Box> fullBoxes){ 

int totalThings = 0; 

for(Box box : fullBoxes){ 
    totalThings += box.getNumThings(); 
} 

return totalThings; 
} 

無論如何,你的代碼無法編譯,例如,在執行此操作屬於?

if (this.numThings > 0) { 
     fullBoxes.add(this); 
} 

請發表評論,我將編輯答案以幫助您。

編輯:可能是你想有這樣的事情,考慮在你的主程序你有一個List<Box>,你可能有這樣的類:

public class Box { 
private int numThings; 

//let it have a random number of things 
public Box(){ 
    this.numThings = RandomHelper.nextIntFromTo(0, 10); 
} 

//make it have certain number of things 
public Box(int numThings) { 
    this.numThings = numThings; 

} 

public static int countNumFromBoxes(List<Box> fullBoxes){ 

    int totalThings = 0; 

    for(Box box : fullBoxes){ 
     totalThings += box.getNumThings(); 
    } 

    return totalThings; 
} 

//GETTERS AND SETTERS 

}