2011-11-14 9 views
1

矩形のarraylistを指定すると、私の仕事は他のすべての矩形を囲む最小の矩形を見つけることです。私がこれまで持って何ArrayList内に他のものを囲むJavaの最小矩形

import java.awt.Rectangle; 
import java.util.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(20, 10, 30, 40)); 
    test.add(new Rectangle(10, 20, 40, 50)); 
    test.add(new Rectangle(20, 10, 50, 30)); 
    Rectangle enc = enclosing(test); 
    System.out.println(enc); 
    System.out.println("Expected: java.awt.Rectangle[x=10,y=10,width=60,height=60]"); 
} 

public static Rectangle enclosing(ArrayList<Rectangle> rects) { 
    // Your work here 
} 
} 

public static Rectangle enclosing(ArrayList<Rectangle> rects) { 
    double topLeftX = Integer.MAX_VALUE; 
    double topLeftY = Integer.MAX_VALUE; 
    double bottomRightX = Integer.MIN_VALUE; 
    double bottomRightY = Integer.MIN_VALUE; 

    for (Rectangle r : rects) { 
     if (r.getX() < topLeftX) 
      topLeftX = r.getX(); 

     if (r.getY() < topLeftY) 
      topLeftY = r.getY(); 

     if ((r.getX() + r.getWidth()) > bottomRightX) 
      bottomRightX = (r.getX() + r.getWidth()); 

     if ((r.getY() + r.getHeight()) > bottomRightY) 
      bottomRightY = (r.getY() + r.getHeight()); 
    } 
    Rectangle.Double enc = new Rectangle.Double(topLeftX, topLeftY, bottomRightX - topLeftX, bottomRightY - topLeftY); 

    return enc; 
} 

私は私のリターンラインのための "互換性のない型" のエラーが表示されます。出力がトップのテスターブロックと一致するようにするには、何がそこに行くのか分かりません。

ありがとうございます!

Rectangle enc = new Rectangle((int) topLeftX, (int) topLeftY, (int) (bottomRightX - topLeftX), (int) (bottomRightY - topLeftY)); 
+1

今後の参考として、適宜宿題タグを使用してください:) – Bryan

+0

なぜ、Rectangleの代わりにRectangle.Doubleを返すのですか? – phatfingers

答えて

1

変更

Rectangle.Double enc = new Rectangle.Double(topLeftX, topLeftY, bottomRightX - topLeftX, bottomRightY - topLeftY); 

ここで何が起こっているあなたは長方形の二つの異なる種類を持っています。整数情報を含む通常のRectangleと、倍精度を含むRectangle.Doubleがあります。戻り値の型はRectangle(整数のバリエーション)なので、Rectangle.Doubleを返すと矛盾します。配列内のすべての長方形が整数精度であることがわかっているので、結果値としてRectangle.DoubleではなくRectangleを使用します。

+1

中間データ型であっても、倍精度を使用する魅力的な理由はないようです。 intを使うだけです。 –

1

に:)

+0

これは本当に残酷なタイプの階層です! –

関連する問題