2段的交集

Intersection of 2 segments

public Segment(Point start, Point end) {
    if (start == null || end == null)
        throw new IllegalArgumentException("Arguments can't be null");
    if (start.equals(end))
        throw new IllegalArgumentException("The points must differ");
    this.start = start;
    this.end = end;

}

public Point intersection(Segment another) {


    div = dy2 * dx1 - dx2 * dy1;

    if (Math.abs(div) < 1.0e-10)
        return null;
   
}

问题是当我想打印时:

Segment first = new Segment(new Point(0, 0), new Point(0, 0));
            Segment second = new Segment(new Point(0, 0), new Point(0, 0));
            Point intersection = first.intersection(second);

            System.out.println(intersection.getX());
            System.out.println(intersection.getY());

出现NullPointerException以防我引入所有坐标0。如何解决这个问题?如果有人可以,请帮忙。我不明白如何捕获此异常或如何解决。

public static Point SegIntersection(double x11, double y11, double x12, double y12,
                                    double x21, double y21, double x22, double y22)
    {
        double dx1 = x12-x11;
        double dy1 = y12-y11;
        double dx2 = x22-x21;
        double dy2 = y22-y21;
        double dxx = x11-x21;
        double dyy = y11-y21;
        double div, t, s;
  
        div = dy2*dx1-dx2*dy1;
        if (Math.abs(div) < 1.0e-10)  //better to compare abs(div) with small Eps
           return null;  //collinear case
        
        t = (dx1*dyy-dy1*dxx) / div;
        if (t < 0 || t > 1.0)
            return null; //intersection outside the first segment

        s = (dx2*dyy-dy2*dxx) / div;
        if (s < 0 || s > 1.0)  
            return null;  //intersection outside the second segment
        return new Point(x11 + s * dx1, y11 + s * dy1);
    }

Quick test

请注意,函数不检查共线段的重叠,因为问题陈述忽略了这种情况。