-2

この Point3f 配列でヌル ポインター例外エラーが発生しましたが、その理由がわかりません。位置 [0] が選択されるのは、最初のパスで発生します。誰でもこれを説明できますか?ありがとう。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.vecmath.Point3f;
public class Starter {

static int NoOfSides = 4;

public static void main(String[] args) {

    Point3f[] pointArray = new Point3f[NoOfSides];

    for(int i=0; i<NoOfSides; i++)
    {
        System.out.println(i+1+". Input x value: ");
        pointArray[i].x=readConsole();      //  Pointer Exception Here

        System.out.println(i+1+". Input y value: ");
        pointArray[i].y=readConsole();

        pointArray[i].z=(float)0.0;
    }
    //  Static call to work out area of polygon
    System.out.println("Area: "+PolyAreaTry.CalArea(pointArray));
}
public static float readConsole()
{
    String s = null;
    try
    {
        BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
        s = bufferRead.readLine();
    }
    catch(IOException e)
    {
        e.printStackTrace();
    }
    float f = (float)Float.parseFloat(s);

    return f;
}

}

4

1 に答える 1

6

Object配列の要素はnullデフォルトです。フィールドへのアクセスを試みる前に、配列自体内の要素を初期化します

for (int i = 0; i < noOfSides; i++) {
   pointArray[i] = new Point3f(); 
   ...
}
于 2013-09-03T23:32:46.383 に答える