2014-09-18 75 views
-1

public class Punct {float 0,y; private float x,y;找不到为什么NullPointerException?

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异常返回给“points [i] .changeCoords(values [j],values [j + 1]);”即使我已经为points []创建实例。

+0

你似乎永远项目分配给您的数组声明数组的每个成员,所以直到你这样做首先你不能使用任何倍。 – 2014-09-18 16:43:51

+0

我不允许这样做:“for(int i = 0; i <2 * n; ++ i){val [i] = i; }”? – nietzche0607 2014-09-18 16:45:13

+0

这与它无关。当你没有将任何对象赋给数组时,你试图在'points [i]'上调用一个方法。 – 2014-09-18 16:45:59

回答

0

1)使用调试器来找出这些问题
2)你的错误是在下面的代码:
之前指数在数组访问对象,确保有一些对象所有,这样你是不是想为非现有(空)对象更改一些值。我在你的代码下面添加了评论。

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; 
    } 
} 
0

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

0

你已经声明了数组。你需要使用新的运营商

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

相关问题