음. 나는 모든 것을 시도했고, 나는이 웹 사이트를 포함하여 인터넷 전체에 대한 답변을 찾고 있었지만, ... 전혀 행운이 없습니다. 여기 변수를 설정할 때 Point [] 배열에서 NullPointerException을 throw합니다.
내 코드입니다 :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());
}
}
}
문제는 아래의 단편의 마지막 줄에서 발생, 오른쪽 배열 "지점 내부의 포인트 개체 중 하나를 사용하려고 시도하는 후 ". 그들은 (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);
오, 좋아요 ... 음, 시도해 볼게요. 작동하는지 확인하겠습니다. 감사합니다;) – Ruyman21
예, 매력처럼 작동합니다. 다음 코드 수정. ;) – Ruyman21