2015-03-03 63 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 

}