鉴于矩形的arraylist,我的任务是找到包围所有其他矩形的最小矩形。
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;
}
我的退货行收到“不兼容的类型”错误。我不确定是什么让输出与顶部的测试器块匹配。
提前致谢! :)
答案 0 :(得分:1)
更改
Rectangle.Double enc = new Rectangle.Double(topLeftX, topLeftY, bottomRightX - topLeftX, bottomRightY - topLeftY);
到
Rectangle enc = new Rectangle((int) topLeftX, (int) topLeftY, (int) (bottomRightX - topLeftX), (int) (bottomRightY - topLeftY));
答案 1 :(得分:1)
这里发生的是你有两种不同类型的矩形。你有正常的Rectangle,它包含整数信息,还有Rectangle.Double,它包含双精度数。由于返回类型是Rectangle(整数变体),因此返回Rectangle.Double是不一致的。由于您知道数组中的所有矩形都是整数精度,因此请使用Rectangle而不是Rectangle.Double作为结果值。