Zoe Taylor
Zoe Taylor

Reputation: 37

Accessing properties of objects in an ArrayList

I need to build a method to find the sum of the areas of the rectangles in a given ArrayList of rectangles.

public class Homework {
public static void main(String[] args) {
    ArrayList<Rectangle> test = new ArrayList<Rectangle>();
    test.add(new Rectangle(10, 20, 30, 40));
    test.add(new Rectangle(10, 10, 30, 40));
    test.add(new Rectangle(20, 20, 40, 50));
    test.add(new Rectangle(20, 10, 50, 30));
    System.out.println(areaSum(test));
    System.out.println("Expected: 5900.0");
    System.out.println(areaAverage(test));
    System.out.println("Expected: 1475.0");
}

public static double areaSum(ArrayList<Rectangle> rects){
    //work goes here
}

What I have so far is:

public static double areaSum(ArrayList<Rectangle> rects){
    double totalArea = 0;
    for (Rectangle r : rects) {
        double area = (x + width) * (y + height);
        totalArea = totalArea + area;
    }
    return totalArea;
}

How can I pull the dimensions of the rectangles from the ArrayList built by the tester block? I'm sort of new to the field, this is a homework assignment and I can't seem to figure it out.

Upvotes: 1

Views: 1114

Answers (2)

Bohemian
Bohemian

Reputation: 424983

area = width * height (not what you have). Correct your calculation.

Also, for more "leetness", use this one liner:

    totalArea += r.getWidth() * r.getHeight();

Upvotes: 1

AlexR
AlexR

Reputation: 115328

Change line that calculates the area to:

double area = r.getWidth() * r.getHeight();

Upvotes: 1

Related Questions