Reputation: 3
Say you define a simple class
public class Box {
double width;
}
and then in Main you have multiple new classes like
Box mybox1 = new Box();
mybox1.width = x
Box mybox2 = new Box();
mybox2.width = y
and after n times
Box myboxn = new Box()
myboxn.width = n
Is there a way to sum up all the *.width with an instruction like:
for each .width
total = total + next.box.width?
Thanks!
Upvotes: 0
Views: 159
Reputation: 684
I'm thinking of using a List to hold all of the widths, then summing them in a for each loop:
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;
Upvotes: 2
Reputation: 1551
Create a Collection
of type Box
and add each box to it as you go. Then you can simply use a for
loop.
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);
}
Upvotes: 2