【发布时间】:2014-11-06 00:49:15
【问题描述】:
我有矩形 A = 左上点 (-4,-1)、右下点 (-2-2) 和矩形 B 左上点 (-2,-2)、右下点 (-1,- 3)
然后:
Rectangle first = new Rectangle(-4,-1,2,1); //x1,y1,width,height
Rectangle second = new Rectangle(-2,-2,1,1);
好的,我有 2 个具有 1 个相同点的矩形。 我使用 first.intersects(second) 并返回 false ..
如何使用 java 来做到这一点,如果矩形 A 中的一个或多个点属于矩形 B,我需要返回 True?
我现在的代码:
公共类 GeometriaRectangle2 {
public static void main(String[] args) {
Scanner lector = new Scanner(System.in);
while (lector.hasNextLine()) {
String a[] = lector.nextLine().split(",");
int b[] = new int[a.length];
for (int i = 0; i < a.length; i++) {
b[i] = Integer.parseInt(a[i]);
}
int c = Math.abs(b[0] - b[2]);
int d = Math.abs(b[1] - b[3]);
int e = Math.abs(b[4] - b[6]);
int f = Math.abs(b[5] - b[7]);
Rectangle r = new Rectangle(b[0], b[1], c, d);
Rectangle r2 = new Rectangle(b[4], b[5], e, f);
int tw = r.width;
int th = r.height;
int rw = r2.width;
int rh = r2.height;
if (rw <= 0 || rh <= 0 || tw <= 0 || th <= 0) {
System.out.println(false);
}
int tx = r.x;
int ty = r.y;
int rx = r2.x;
int ry = r2.y;
rw += rx;
rh += ry;
tw += tx;
th += ty;
// overflow || intersect or attached
if ((rw < rx || rw >= tx) && (rh < ry || rh >= ty)
&& (tw < tx || tw >= rx) && (th < ty || th >= ry)) {
System.out.println(true);
} else {
System.out.println(false);
}
}
}
}
示例:输入:
-3,3,-1,1,1,-1,3,-3
-3,3,-1,1,-2,4,2,2
输出:
错误
是的
【问题讨论】:
-
根据你的例子,这两个矩形不感兴趣......
-
Java 已经为你处理了这个问题:
Rectangle intersection = first.intersection(second);或者你可以用这个answer写一个... -
@Mr.Polywhirl 返回
false,因为这两个矩形不重叠...
标签: java