2014-09-18 77 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(); }

相關問題