2017-03-17 43 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); 
} 
相關問題