Java、两个矩形

编写一个程序,提示用户输入两个矩形中心的 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";	//相离
	}
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值