2017-03-17 40 views
0

说你定义一个简单的类如何几经类新的总结类似的变量()已生成

public class Box { 
double width; 
} 

,然后在主你有多个新的类,如

Box mybox1 = new Box(); 
mybox1.width = x 
Box mybox2 = new Box(); 
mybox2.width = y 

后n次

Box myboxn = new Box() 
myboxn.width = n 

有没有办法来总结所有的* .WIDTH的指令,如:

for each .width 
total = total + next.box.width? 

谢谢!

+1

简短的回答不,不知道怎么会有人迭过一些稀薄的空气?因此,将这些框存储在'java.util.List'中,然后迭代列表 – 2017-03-17 19:38:40

+1

,因为您已经循环n次创建Boxes,只需在创建和设置宽度时将它们添加到像Arraylist这样的数据结构。然后为数据结构中的每个盒子添加一个宽度。 –

回答

2

我想用List来存储所有的宽度,然后总结他们在每个循环的:

List<Double> widths=new ArrayList<>(); 

//declare all your new classes in Main and add their widths to the list 
Box mybox1 = new Box(); 
widths.add(mybox1.width); 
Box mybox2 = new Box(); 
widths.add(mybox2.width); 

//then sum the widths 
double totalWidth; 
for(Double tempWidth:widths) 
    totalWidth+=tempWidth; 
+0

谢谢,这工作得很好! – fdamico

2

创建BoxCollection每个框添加到它,你去。然后你可以简单地使用for循环。

public class Box { 
    int width; 
    public Box(int width) { 
     this.width = width; 
    } 

    public int getWidth() { 
     return this.width; 
    } 
} 

... 

public static void main(String args[]) { 
    Collection<Box> boxes = new ArrayList<Box>(); 
    boxes.add(new Box(1)); 
    boxes.add(new Box(2)); 
    boxes.add(new Box(3)); 
    boxes.add(new Box(4)); 

    int total = 0; 
    for(Box box : boxes) { 
     total = total + box.getWidth(); 
    } 
    System.out.println("Total widths: " + total); 
} 
相关问题