Home > Enterprise >  Intersection of 2 segments
Intersection of 2 segments

Time:09-22

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;
   
}

Problem is that when I want to print:

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());

appear NullPointerExceptionin case when I introduced all coordinates 0. How to solve this? Help please if anybody can. I not understand how to catch this exception or how to solve.

CodePudding user response:

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

Note that function does not check overlapping of collinear segments, because problem statement ignores such case.

  • Related