编写一个程序,提示用户输入两个矩形中心的 x 坐标和 y 坐标以及矩形的宽度和高度,然后判断第二个矩形是在第一个矩形内,还是和第一个矩形重叠。
提示:
- 一个矩形(中心(x2, y2))在另一个矩形(中心(x1, y1))内:两个中心距离在x、y上的分量假设为x0, y0, 中心(x1, y1)的高为 h1,宽为w1。中心(x2, y2)的高为 h2, 宽为w2。满足(x0 + w2/2)< (w1 / 2),且(y0 + h2/2) < (h1 / 2)。
- 重叠:(w1 - w2)/ 2 < x0 < (w1 + w2) / 2 且(h1 - h2)/ 2 < y0 < (h1 + h2) / 2
- 相离:x0 > (w1 + w2)/ 2 或 y0 > (h1 + h2) / 2
package pack2;
import java.util.Scanner;
import javafx.geometry.Point2D;
public class TwoRectangle {
public static void main(String[] args) {
try(Scanner input = new Scanner(System.in);) {
System.out.print("Enter r1's center x-, y-coordinates, width, and height: ");
double x1 = input.nextDouble(), y1 = input.nextDouble();
double w1 = input.nextDouble(), h1 = input.nextDouble();
System.out.print("Enter r2's center x-, y-coordinates, width, and height: ");
double x2 = input.nextDouble(), y2 = input.nextDouble();
double w2 = input.nextDouble(), h2 = input.nextDouble();
System.out.println(judge(new Point2D(x1, y1), w1, h1, new Point2D(x2, y2),
w2, h2));
}
}
//判定两个矩形
public static String judge(Point2D r1, double w1, double h1, Point2D r2, double w2,
double h2) {
double x0 = Math.abs(r2.getX() - r1.getX()); //分量x
double y0 = Math.abs(r2.getY() - r1.getY()); //分量y
if((x0 + w2 / 2 <= w1 / 2) && (y0 + h2 / 2 <= h1 / 2)) //一个矩形在另一个矩形内
return "r2 is inside r1";
else if((w1 - w2) / 2 < x0 && x0 <(w1 + w2) / 2 && (h1 - h2) / 2 < y0 &&
y0 < (h1 + h2) / 2)
return "r2 overlaps r1"; //重叠
else
return "r2 does not overlap r1"; //相离
}
}