矩形の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));
今後の参考として、適宜宿題タグを使用してください:) – Bryan
なぜ、Rectangleの代わりにRectangle.Doubleを返すのですか? – phatfingers