Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/389.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 计算两个相同对象的交点_Java_Math_Intersection_Rectangles - Fatal编程技术网

Java 计算两个相同对象的交点

Java 计算两个相同对象的交点,java,math,intersection,rectangles,Java,Math,Intersection,Rectangles,我有两个矩形,它们都有相同的边 new Rectangle(Arrays.asList(new Coord(1,1), new Coord(2,1), new Coord(2,2), new Coord(1,2))); 根据我的理解,交叉点应该是1,但是我的函数返回-1 public Rectangle(List<Coord> edges){ Assert.assertTrue("Provide an exact number of 4 edges", edges.

我有两个矩形,它们都有相同的边

new Rectangle(Arrays.asList(new Coord(1,1), new Coord(2,1), new Coord(2,2), new Coord(1,2)));
根据我的理解,交叉点应该是
1
,但是我的函数返回
-1

public Rectangle(List<Coord> edges){
        Assert.assertTrue("Provide an exact number of 4 edges", edges.size() == 4);
        this.edges = edges;
        left = getLeft(edges);
        right = getRight(edges);
        top = getTop(edges);
        bottom = getBottom(edges);
    }

private static int computeIntersection(Rectangle rect1, Rectangle rect2){

        int x_overlap = Math.min(rect1.right, rect2.right) - Math.max(rect1.left, rect2.left);
        int y_overlap = Math.min(rect1.bottom,rect2.bottom) - Math.max(rect1.top,rect2.top);
        System.out.println(x_overlap * y_overlap);


        return x_overlap * y_overlap;

    }
公共矩形(列出边){
Assert.assertTrue(“提供精确的4条边数”,edges.size()==4);
这个。边=边;
左=左(边);
右=右(边);
顶部=getTop(边缘);
底部=底部(边缘);
}
私有静态int-computeIntersection(矩形rect1,矩形rect2){
int x_overlap=Math.min(rect1.right,rect2.right)-Math.max(rect1.left,rect2.left);
int y_overlap=Math.min(rect1.bottom,rect2.bottom)-Math.max(rect1.top,rect2.top);
System.out.println(x_重叠*y_重叠);
返回x_重叠*y_重叠;
}

在计算交叉点时,我的数学有问题吗?或者我没有考虑什么?

首先,你应该检查这两个矩形是否实际上是重叠的。

并且,您应该使用最小值
顶部
减去最大值
底部

private static int computeIntersection(Rectangle rect1, Rectangle rect2){
    if (rect1.left >= rect2.right || rect2.left >= rect1.right
            || rect1.bottom >= rect2.top || rect2.bottom >= rect1.top) {
        return 0;
    } else {
        int x_overlap = Math.min(rect1.right, rect2.right) - Math.max(rect1.left, rect2.left);
        int y_overlap = Math.min(rect1.top,rect2.top) - Math.max(rect1.bottom,rect2.bottom);
        return x_overlap * y_overlap;
    }
}

x\u重叠
为1,
y\u重叠
为-1。在x或y之间切换差值。@luk2302但这不是找到交叉点的实际定义吗?!我对此表示怀疑,我不知道这个值应该代表什么。这看起来毫无意义。如果有什么,我希望两个相同的对象的值为0。我刚刚告诉过你,输出应该看你的代码,它是有用的还是正确的完全是另一回事。你为什么发布这些方法getLeft、getTop等等?你没有在你的代码中使用它们,我用它们来设置值。我会更新的。太好了,是的,我弄错了你的重叠
顶部和底部
。谢谢你的澄清