Java 在数据集中查找最近的对给出 NullPointerException

Java Find Closest Pair in Dataset gives NullPointerException

我试图从几个不同的数据集中找到最接近的对。到目前为止,它适用于具有 12 个点的 SmallerSet,但是当我更改具有 100 个点的数据集时。它在我在循环之前添加“--->”的行中给出 NullPointer Excepiton。我不知道要解决它。

public static PointPair closestPair(Point2D.Double Px[], Point2D.Double Py[],int n) {
    PointPair closestpairLeft;
    PointPair closestpairRight;

    if (n <= 3) {
        if(n==2)
            return new PointPair(Px[0],Px[1]);
        else{
        PointPair p1=new PointPair(Px[0],Px[1]);
        PointPair p2=new PointPair(Px[0],Px[2]);
        PointPair p3=new PointPair(Px[1],Px[2]);

        if(p1.closerThan(p2)<0){
            if(p1.closerThan(p3)<0)
                return p1;
            else
                return p3;
        }
        else{
            if(p2.closerThan(p3)<0)
                return p2;
            else
                return p3;
        }
        }
    } else {
        int mid = n / 2;


        Point2D.Double Xl[] = Arrays.copyOfRange(Px, 0, mid);
        Point2D.Double Xr[] = Arrays.copyOfRange(Px, mid, n);

        Point2D.Double Yl[] = new Point2D.Double[Xl.length];
        Point2D.Double Yr[] = new Point2D.Double[Xr.length];


       ---> for (int i = 0, k = 0, j = 0; i < n; i++) {
            if (Py[i].getX() <= Xl[mid-1].getX()&& j<mid) {
                Yl[j++] = Py[i];
            } else if (k<mid){
                Yr[k++] = Py[i];

            }

        }

        closestpairLeft=closestPair(Xl,Yl,mid);
        closestpairRight=closestPair(Xr,Yr,n-mid);
    }

按如下操作:

for (int i = 0, k = 0, j = 0; i < n && i < Py.length && (mid - 1) < Xl.length && j < Yl.length
        && k < Yr.length; i++) {
    if (Py[i] != null && Xl[mid - 1] != null && Py[i].getX() <= Xl[mid - 1].getX() && j < mid) {
        Yl[j++] = Py[i];
    } else if (k < mid) {
        Yr[k++] = Py[i];
    }
}

请注意,我不仅为 null 检查了 Py[i]Xl[mid-1],而且还检查了数组的边界以避免 ArrayIndexOutOfBoundsException