数组异常错误,Point3f数组

时间:2013-09-03 23:31:16

标签: java arrays

我在这个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;
}

}

1 个答案:

答案 0 :(得分:6)

默认情况下,Object数组的元素为null。在尝试访问其字段之前初始化数组本身中的元素

for (int i = 0; i < noOfSides; i++) {
   pointArray[i] = new Point3f(); 
   ...
}