在java中添加实例变量的值

时间:2015-03-03 00:52:11

标签: java

编辑:暂时失去了我的大脑。道歉。

如果列表中有n个Box对象,其实例变量名为numThings(每个框中的数字)。每个框中的numThings是随机的。如何计算每个框中的所有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()
          }
     }   


}

2 个答案:

答案 0 :(得分:1)

一个简单的实现可以是:

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

答案 1 :(得分: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

}