该程序假设接收两个矩形的(x,y)坐标和宽度和高度,并显示两个带有字符串的矩形,表示它们重叠,包含或不重叠。我有正确的图形。但我的问题在于要显示的字符串的逻辑。当用户输入未包含或彼此重叠的三角形的数据时。它说它们重叠。我需要帮助修复代码的逻辑。
uuid
答案 0 :(得分:0)
嗯,“包含”很容易:
boolean contain = rect1.contains(rect2) || rect2.contains(rect1);
之后,“重叠”很容易:
boolean overlap = ! contain && rect1.intersects(rect2);
或者,获取你的字符串:
String s = (rect1.contains(rect2) || rect2.contains(rect1)
? "One rectangle is contained in another."
: rect1.intersects(rect2)
? "One rectangle overlaps another."
: "The rectangles do not overlap.");
答案 1 :(得分:0)
看起来你的主要问题是你的“包含”检查。它只考虑矩形的宽度和高度,而不是它们所在的位置。您可以编写一个“包含”方法,如:
private static boolean contains(Rectangle r1, Rectangle r2) {
return r1.getX() <= r2.getX() && r1.getY() <= r2.getY()
&& r2.getX() + r2.getWidth() <= r1.getX() + r1.getWidth()
&& r2.getY() + r2.getHeight() <= r1.getY() + r1.getHeight();
}
然后将支票更改为
if (contains(rec1, rec2) || contains(rec2, rec1)) {
s = "One rectangle is contained in another.";
} else if (rec1.intersects(rec2.getX(), rec2.getY(), rec2.getWidth(), rec2.getHeight())) {
s = "One rectangle overlaps another.";
} else {
s = "The rectangles do not overlap.";
}
(你只需要单向检查交叉点,因为如果矩形A与B相交,那么B也与A相交。)