2011-11-13 39 views
1

我需要構建一個方法來查找給定矩形區域中矩形區域的總和。訪問ArrayList中對象的屬性

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 
} 

我至今是:

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; 
} 

我怎麼能拉矩形的尺寸通過測塊建造的ArrayList?我對這個領域很陌生,這是一項家庭作業,我似乎無法弄清楚。

回答

1

更改行計算面積:

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

1

area = width * height(你不是)。糾正你的計算。

此外,對於更多的 「leetness」,用這一個班輪:

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