###### 新手小白学习java,遇到需要求解让用户输入两个矩形的坐标和长宽来判断两个矩形的相交情况,浅记录一下这个算法
######
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("输入第一个矩形的x, y, width and height :");
double x1 = input.nextDouble();
double y1 = input.nextDouble();
double w1 = input.nextDouble();
double h1 = input.nextDouble();
double lx1 = x1-(w1/2);
double ly1 = y1-(h1/2);
double rx1 = x1+(w1/2);
double ry1 = y1+(h1/2);
//矩形1的右下坐标(lx1,ly1);左上坐标(rx1,ry1)
System.out.println("输入第二个矩形的x, y, width and height :");
double x2 = input.nextDouble();
double y2 = input.nextDouble();
double w2 = input.nextDouble();
double h2 = input.nextDouble();
double lx2 = x2-(w2/2);
double ly2 = y2-(h2/2);
double rx2 = x2+(w2/2);
double ry2 = y2+(h2/2);
//矩形2的左下坐标(lx2,ly2);右上坐标(rx2,ry2);
double []rec1 = {lx1,ly1,rx1,ry1};
double []rec2 = {lx2,ly2,rx2,ry2};
//选择开始
if(rec2[1] >= rec1[3] || rec1[1] >= rec2[3]) {
System.out.println(" 两个矩形不相交 ");
}
else if(rec1[0] >= rec2[2] || rec1[2] <= rec2[0]){
System.out.println(" 两个矩形不相交 ");
}
//判定两个矩形不相交
else if ( rec1[0] <= rec2[0] && rec1[1] <= rec2[1] && rec2[2] <= rec1[2] && rec2[3] <= rec1[3] ) {
System.out.println(" 第二个矩形包括了第一个矩形 ");
}
else if ( rec2[0] <= rec1[0] && rec2[1] <= rec1[1] && rec1[2] <= rec2[2] && rec1[3] <= rec2[3] ) {
System.out.println(" 第一个矩形包括了第二个矩形 ");
}
//判断两个矩形是否包含
else
{
System.out.println(" 两矩形相交 ");
}
//判定两个矩形相交
还有一种判断两个相交的部分的代码:(后面发现直接else就可以,因为两个矩形不是不相交就是相交)
else if ( ( rec2[0]<rec1[0] && rec1[0]<rec2[2] ) || ( rec2[0]<rec1[2] && rec1[2]<rec2[2] ) )
{
System.out.println(" 两矩形相交 ");
}
else if ( ( rec2[1]<rec1[1] && rec1[1]<rec2[3] ) || ( rec2[1]<rec1[3] && rec1[3]<rec2[3] ) )
{
System.out.println(" 两矩形相交 ");
}
//判定两个矩形相交
原理是通过找到两个矩形最左下的坐标和最右上的坐标来进行各种情况判断的分析