2014-09-08 6 views
1

음. 나는 모든 것을 시도했고, 나는이 웹 사이트를 포함하여 인터넷 전체에 대한 답변을 찾고 있었지만, ... 전혀 행운이 없습니다. 여기 변수를 설정할 때 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); 

답변

5

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); 
    ... 
+0

오, 좋아요 ... 음, 시도해 볼게요. 작동하는지 확인하겠습니다. 감사합니다;) – Ruyman21

+0

예, 매력처럼 작동합니다. 다음 코드 수정. ;) – Ruyman21

0

yshavit의 조언을 다음과 코드를 약간 수정 후이가 종료 방법이다.

/* 
* 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()); 
     } 
    } 
} 
관련 문제