当我尝试运行程序时,我在第8行得到一个空指针异常,(basePoints [i] .x3D =(int)(R Math.cos(i T)); )。这在运行时i = 0时立即发生。我不明白我做错了什么我已经初始化了basePoints,(Point3D [] basePoints = new Point3D [50];)
有人可以帮帮我吗?
Cone newCone = new Cone();
final int H = newCone.HEIGHT;
final int R = newCone.RADIUS;
Point3D[] basePoints = new Point3D[50]; //50 points around the base of the cone
final double T = 2*Math.PI/basePoints.length;
for (int i = 0; i < basePoints.length; i++) {
basePoints[i].x3D = (int) (R*Math.cos(i*T));
basePoints[i].y3D = (int) (R*Math.sin(i*T));
}
答案 0 :(得分:0)
我认为你的循环中的第一行应该是basePoints[i] = new Point3D();
所以循环是:
for (int i = 0; i < basePoints.length; i++) {
basePoints[i] = new Point3D();
basePoints[i].x3D = (int) (R*Math.cos(i*T));
basePoints[i].y3D = (int) (R*Math.sin(i*T));
}
行Point3D[] basePoints = new Point3D[50];
在内存中为50个Point3D实例保留空间,但它不会初始化它们。
答案 1 :(得分:0)
您需要创建一个新的Point3D
对象,并在为其赋值之前将其放入数组位置:
...
for (int i = 0; i < basePoints.length; i++) {
basePoints[i] = new Point3D();
basePoints[i].x3D = (int) (R*Math.cos(i*T));
basePoints[i].y3D = (int) (R*Math.sin(i*T));
}
...