Массив Point[] выдает исключение NullPointerException при попытке установить переменные

Что ж. Я пробовал ВСЕ, и я искал ответы по всему интернету, включая этот сайт, но... Не повезло вообще.

Вот мой код:

package com.exercises.algorithms;
import java.awt.*;


public class Points2DN {
    private Point[] points;
    protected int[] closestPoints = new int[2];
    private double distance;

Points2DN(int n) {
    this.points = new Point[n];
    for (int i = 0; i < n; i++) {
        this.points[i].x =  (int) Math.floor(Math.random()*100);
        this.points[i].y =  (int) Math.floor(Math.random()*100);
        System.out.println("Test: " + points[i].x + "," + points[i].y + "\n");
        System.out.println("OK");
    }
    this.distances(this);
}


public static void imprimePuntos(Point[] arrayPuntos) {
    for (int i = 0; i < arrayPuntos.length; i++) {
        System.out.println("Punto " +(i+1) + ": " + "( "
                + arrayPuntos[i].x + " , "
                + arrayPuntos[i].y + " )");
    }
}

public static void printClosest(Points2DN puntos) {
    System.out.println("\nLos puntos más cercanos son: ");
    System.out.println("Puntos: \t" 
            + (puntos.points[puntos.closestPoints[0]]).toString() + " "
            + (puntos.points[puntos.closestPoints[1]]).toString());
    System.out.println("Distancia: " + puntos.distance);


}

private void distances(Points2DN puntos) {
    for (int i = 0; i < puntos.points.length; i++) {
            // Iterative loop for the other points to be check with
        for (int j = (i+1); j < this.points.length; j++) {
            if (i == 0 && j == 1) {
                int p = puntos.closestPoints[0] = i;
                int q = puntos.closestPoints[1] = j;
                puntos.distance = (puntos.points[p]).distance(puntos.points[q]);
                continue;
            }
            double distancePair = puntos.points[i].distance(puntos.points[j]);
            if (distancePair < puntos.distance){
                puntos.closestPoints[0] = i;
                puntos.closestPoints[1] = j;
                puntos.distance = distancePair;
            }
        }
    }
}


public static void main(String[] args) {
    try {
        int numberOfPoints = Integer.parseInt(args[0]);
        if (args.length == 1) {
            System.out.println("Calculando...");
            Points2DN puntos = new Points2DN(numberOfPoints);
            imprimePuntos(puntos.points);
            printClosest(puntos);
        }

        else {
            // Nothing
        }

    } catch (ArrayIndexOutOfBoundsException e) {
        System.out.println("Not a valid number of points");
    } catch (Exception e) {
        System.out.println(e.toString());
    }

}

}

Проблема возникает в последней строке фрагмента ниже, сразу после попытки использовать один из объектов Point внутри массива "points". Они должны быть заполнены значениями типа "int" (0,0) на (x,y) и инициализированы. Я проверил размер с:

 points.length

И результатом является число, которое я установил в качестве аргумента в моей IDE для запуска проекта. Например, если 'n' равно 10, это значение равно 10. Это нормально, так что... ПОЧЕМУ, АД, это не работает!??

 Points2DN(int n) {
    this.points = new Point[n];
    for (int i = 0; i < n; i++) {
        this.points[i].x =  (int) Math.floor(Math.random()*100);

2 ответа

Решение

new Point[n] создает массив Pointс, но это не создает никакого фактического Point объекты, чтобы сидеть в этом массиве. Это все равно что покупать коробку, в которой можно хранить книги - в ней нет книг, пока вы не положите их туда.

Вам нужно создать Point для каждого элемента индекса, который вы хотите использовать, что-то вроде:

for (int i = 0; i < n; i++) {
    points[i] = new Point();
    points[i].x =  (int) Math.floor(Math.random()*100);
    ...

После следования совету Ишавита и небольшого исправления кода, так все и закончилось.

/*
 * Points2DN - Algorithms to calculate distance in 2D
 *
 * Author:
 * @Ruyman
 */

package com.exercises.algorithms;
import java.awt.*;
// import java.util.*;
import java.math.BigDecimal;
import java.math.RoundingMode;

public class Points2DN {
    private Point[] points;
    protected int[] closestPoints = new int[2];
    private BigDecimal distance;

    Points2DN(int n) {
        this.points = new Point[n];
        for (int i = 0; i < n; i++) {
            this.points[i] = new Point();
            this.points[i].x =  (int) Math.floor(Math.random()*100);
            this.points[i].y =  (int) Math.floor(Math.random()*100);
        }
        this.distances(this);
    }

    Points2DN(int n, int x) {
        this.points = new Point[n];
        for (int i = 0; i < n; i++) {
            this.points[i] = new Point();
            this.points[i].x =  (int) Math.floor(Math.random()*100);
            this.points[i].y =  (int) Math.floor(Math.random()*100);
        }
        this.distances(this, x);
    }

    public static void imprimePuntos(Point[] arrayPuntos) {
        for (int i = 0; i < arrayPuntos.length; i++) {
            System.out.println("Point2D " +(i+1) + ": " + "( "
                    + arrayPuntos[i].x + " , "
                    + arrayPuntos[i].y + " )");
        }
    }

    public static void printClosest(Points2DN puntos) {
        Point p = puntos.points[puntos.closestPoints[0]];
        Point q = puntos.points[puntos.closestPoints[1]];
        System.out.println("\nThe closest points are: ");
        System.out.println("Points: "
                    + "(" + p.x + "," + p.y + ")" + " & "
                    + "(" + q.x + "," + q.y + ")");
        System.out.println("Distance: " + puntos.distance);
    }

    private void distances(Points2DN puntos) {
        for (int i = 0; i < puntos.points.length; i++) {
        // Iterative loop for the other points to be check with
            for (int j = (i+1); j < this.points.length; j++) {
                if (i == 0 && j == 1) {
                    int p = puntos.closestPoints[0] = i;
                    int q = puntos.closestPoints[1] = j;
                    puntos.distance = new BigDecimal((puntos.points[p]).distance(puntos.points[q])).setScale(3, RoundingMode.FLOOR);
                    continue;
                }
                BigDecimal distancePair = new BigDecimal(puntos.points[i].distance(puntos.points[j]));
                if (distancePair.doubleValue() < puntos.distance.doubleValue()){
                    puntos.closestPoints[0] = i;
                    puntos.closestPoints[1] = j;
                    puntos.distance = distancePair.setScale(3, RoundingMode.FLOOR);
                }
            }
        }
    }

    private void distances(Points2DN puntos, int x) {
        for (int i = 0; i < puntos.points.length; i++) {
            // Iterative loop for the other points to be check with
            for (int j = (i+1); j < this.points.length; j++) {
                if (i == 0 && j == 1) {
                    int p = puntos.closestPoints[0] = i;
                    int q = puntos.closestPoints[1] = j;
                    puntos.distance = new BigDecimal((puntos.points[p]).distance(puntos.points[q])).setScale(x, RoundingMode.FLOOR);
                    continue;
                }
                BigDecimal distancePair = new BigDecimal(puntos.points[i].distance(puntos.points[j]));
                if (distancePair.doubleValue() < puntos.distance.doubleValue()){
                    puntos.closestPoints[0] = i;
                    puntos.closestPoints[1] = j;
                    puntos.distance = distancePair.setScale(x, RoundingMode.FLOOR);
                }
            }
        }
    }

    /* main (String n, string x) {}
     * Generates 'n' random 2D points
     * Calculates which pair is the closest one
     * Print the result including the distance with 'x' decimals
     */ 

    public static void main(String[] args) {
        try {
            int numberOfPoints = Integer.parseInt(args[0]);
            if (args.length == 1) {
                Points2DN puntos = new Points2DN(numberOfPoints);
                imprimePuntos(puntos.points);
                printClosest(puntos);
            }

            if (args.length == 2) {
                int x = Integer.parseInt(args[1]);
                Points2DN puntos = new Points2DN(numberOfPoints, x);
                imprimePuntos(puntos.points);
                printClosest(puntos);
            }
        } catch (Exception ex) {
            System.out.println(ex.toString());
        }
    }
}
Другие вопросы по тегам