无法解释为什么NullPointerException?

时间:2014-09-18 16:41:45

标签: java nullpointerexception null

public class Punct {     private float x,y;

public Punct ( float x, float y ) {
    this.x = x;
    this.y = y;
}

public void changeCoords ( float x, float y ) {
    this.x = x;
    this.y = y;
}

public void displayCoords() {
    System.out.println ( "( " + x + ", " + y + " )" );
}

}

公共课Poligon {

Punct points[];

public Poligon ( int num, float values[] ) {
    points = new Punct[num];
    int j = 0;

    for ( int i = 0; i < num; ++i ) {
            points[i].changeCoords(values[j], values[j+1]);
            j+=2;   
    }
}

public void displayPoligon( int nr ) {
    for ( int i = 0; i < nr; ++i ) {
        points[i].displayCoords();
    }
}

}

公共课堂考试{

public static void main(String[] args) {

    int n = 3;
    float val[] = new float[2*n];

    for ( int i = 0; i < 2*n; ++i ) {
        val[i] = i;
    }

    Poligon a = new Poligon(n, val);
    a.displayPoligon(n);
}

}

当我编译这段代码时,它会将java.lang.NullPointerException返回给第&#34; points [i] .changeCoords(values [j],values [j + 1]);&#34;即使我已经为点[]创建了实例。

3 个答案:

答案 0 :(得分:0)

您有一个points[]的实例,但该数组没有元素,因此特定元素points[i]为空。

答案 1 :(得分:0)

1)使用调试器来查找此类问题
2)您的错误在以下代码中:
在通过索引访问数组中的对象之前,请确保存在一些对象,这样您就不会尝试更改非现有(null)对象的某些值。我在你的代码下面添加了评论。

public Poligon(int num, float values[]) {
    points = new Punct[num]; -- here you created an EMPTY array, it will have a length, but it is without any objects yet 
    int j = 0;

    for (int i = 0; i < num; ++i) { 
        points[i].changeCoords(values[j], values[j + 1]); // here is exception. You are trying to change Coords for NULL object
        j += 2;
    }
}

答案 2 :(得分:0)

你已经声明了数组。你需要使用new operator

声明数组的每个成员

for (int i = 0; i < num ; i++) { points[i] = new Punct(); }