写点阵列

时间:2016-10-09 18:09:09

标签: arrays input point

我使用trainigs代码来比较非特定点数与零点的距离。

当我想将输入点值写入Point数组并且我不知道如何处理它时,会出现错误:

points[i].setLocation(x,y);

错误说:线程中的异常" main"显示java.lang.NullPointerException 在minDis.minDis.main(minDis.java:59)

我会感谢任何建议。

import java.awt.Point;
import java.util.Scanner;

public class minDis {

private static final Point Point = null;


static double dis(Point p){

    double dis= Math.sqrt(p.x*p.x+p.y*p.y);

    return dis;
}


static double minDist(Point[] points, int anz){

double minimum= dis(points[0]);


    for(int z=0; z<anz; z++){
        if (dis(points[z]) < minimum)
            minimum=dis(points[z]);
    }
    return minimum;
}

static double minDistPoint(Point[] points, int anz){

    double minimum= dis(points[0]);
    int DistPoint = 0;

        for(int z=0; z<anz; z++){
            if (dis(points[z]) < minimum)
                minimum=dis(points[z]);
                DistPoint=z;
        }
        return DistPoint;
    }


public static void main(String[] args) {
    Point points[]=null;
    Scanner scan= new Scanner(System.in);
    System.out.println("How many Points do you want to compare?");
    int anz= scan.nextInt();
    for(int i=0; i<anz; i++){
        System.out.println("Type in Point "+anz);
        System.out.println("X: ");
        int x= scan.nextInt();
        System.out.println("Y: ");
        int y= scan.nextInt();
        **points[i].setLocation(x,y);**

    }
    scan.close();

    System.out.println("It is Point "+minDistPoint(points, anz)+" with a distance of "+ minDist(points, anz));




}

}

1 个答案:

答案 0 :(得分:0)

在您的代码段中,您没有为Pointer Object数组分配内存。这就是你得到NullPointerException的原因。因此,您需要将内存分配给代码中的Point对象数组。

但是,请记住在创建像这样的对象数组时,

Object[] arr = new Object[10];

在这里,您只需创建10个对象引用。现在,要对单个数组元素执行任何操作,您还需要为每个对象分配内存,例如,

arr[i] = new Object();

因此,请使用以下代码段作为代码的更正版本。

public static void main(String[] args) {
    Point[] points;
    Scanner scan= new Scanner(System.in);
    System.out.println("How many Points do you want to compare?");
    int anz= scan.nextInt();
    points = new Point[anz];
    for(int i=0; i<anz; i++) {
        points[i] = new Point();
        System.out.println("Type in Point "+anz);
        System.out.println("X: ");
        int x= scan.nextInt();
        System.out.println("Y: ");
        int y= scan.nextInt();
        points[i].setLocation(x,y);   
    }
    scan.close();
    System.out.println("It is Point "+ minDistPoint(points, anz)+" with a distance of "+ minDist(points, anz));
}