Introduction to Java Programming编程题3.28<判断两个长方形是否相交>

/*
Enter r1's center x-, y-coordinates, width, and height:2.5 4 2.5 43
Enter r2's cneter x-, y-coordinates, width, and height:1.5 5 0.5 3
r2 is inside r1

Enter r1's center x-, y-coordinates, width, and height:1 2 3 5.5
Enter r2's cneter x-, y-coordinates, width, and height:3 4 4.5 5
r2 overlaps r1

Enter r1's center x-, y-coordinates, width, and height:1 2 3 3
Enter r2's cneter x-, y-coordinates, width, and height:40 45 3 2
r2 does not overlap r1
 */

import java.util.Scanner;

public class TwoRectangle {

    public static void main(String[] args) {

       Scanner input = new Scanner(System.in);

        System.out.print("Enter r1's center x-, y-coordinates, width, and height:");
        double r1CenterX = input.nextDouble();
        double r1CenterY = input.nextDouble();
        double r1Width = input.nextDouble();
        double r1Height = input.nextDouble();
        System.out.print("Enter r2's cneter x-, y-coordinates, width, and height:");
        double r2CenterX = input.nextDouble();
        double r2CenterY = input.nextDouble();
        double r2Width = input.nextDouble();
        double r2Height = input.nextDouble();

        double r1MaxDistance = Math.sqrt(r1Width * r1Width + r1Height * r1Height) / 2;
        double r2MaxDistance = Math.sqrt(r2Width * r2Width + r2Height * r2Height) / 2;
        double insideMaxDistance = r1MaxDistance - r2MaxDistance;
        double overLapsMaxDistance = r1MaxDistance + r2MaxDistance;
        double r2ToR1Distance = Math.sqrt(Math.abs((r1CenterX - r2CenterX) * (r1CenterX - r2CenterX))
                + Math.abs((r1CenterY - r2CenterY) * (r1CenterY - r2CenterY)));

        if(r2ToR1Distance <= insideMaxDistance)
            System.out.println("r2 is inside r1");
        else if(r2ToR1Distance <= overLapsMaxDistance)
            System.out.println("r2 overlaps r1 ");
        else
            System.out.println("r2 does not overlap r1");
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值