嗯。我什么都试过了,我一直在整个互联网上寻找答案,包括这个网站,但是......一点运气都没有。
这是我的代码:
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());
}
}
问题发生在下面片段的最后一行,就在尝试使用数组“points”中的一个 Point 对象之后。它们应在 (x,y) 上填充“int”类型值 (0,0),并进行初始化。我已经检查了尺寸:
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);
最佳答案
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);
...
关于java - Point[] 数组在尝试设置变量时抛出 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25730226/