提问人:suk1 提问时间:11/12/2022 更新时间:11/12/2022 访问量:50
Java class[i].subclass 异常无法读取字段“subclass”,因为 class[i] 为 null [duplicate]
Java class[i].subclass exception cannot read feild "subclass" because class[i] is null [duplicate]
问:
感谢您的观看。让我们直奔主题。
这是我的班级的样子
`
class Moon{
double distance;
double angle;
double diameter;
String col;
double centreOfRotationDistance;
double centreOfRotationAngle;
}
class Planet{
double distance;
double angle;
double diameter;
String col;
Moon moon = new Moon();
}
`
但是,当我尝试像这样访问时,java 会抛出 .
我的代码出了什么问题吗?如果是,我该如何解决?Planet[i].moon
NullPointerException
`
System.out.println("Creating planets...");
String[] colArray = {"red", "orange", "yellow", "green", "blue", "indigo", "violet", "white", "red"};
for(int i = 0; i < 8; i++){
planets[i] = new Planet();
planets[i].distance = 100 + (i * 100);
planets[i].angle = 0 + (i * 20);
planets[i].diameter = 20 + (i * 10);
planets[i].col = colArray[i];
System.out.println("Planet " + i + " created");
System.out.println("Creating moon..." + i);
planets[i].moon.distance = 10 + (i * 5);
planets[i].moon.angle = 0 + (i * 20);
planets[i].moon.diameter = i + 2;
planets[i].moon.col = colArray[i++];
planets[i].moon.centreOfRotationDistance = (100 + (i * 100))/10;
planets[i].moon.centreOfRotationAngle = 0 - (i * 20);
}
System.out.println("Done creating planets.");
System.out.println("Creating the sun...");
`
堆栈,以防有用
再次感谢您的阅读/回答
我的原始代码是这样的
我以为我可能太雄心勃勃了,无法进入我正在创建的类并从中获取价值。 因此,我尝试将代码更改为上面的代码片段,但是它不起作用?
问了几个朋友,没有人知道为什么会出错。因此发布
答:
3赞
Jon Skeet
11/12/2022
#1
这些行是问题所在:
planets[i].moon.col = colArray[i++];
planets[i].moon.centreOfRotationDistance = (100 + (i * 100))/10;
在第一行中,您正在递增 - 这意味着在下一行中,引用元素仍为 null 的数组索引。i
planets[i]
我怀疑这个简单的更改可以解决问题:
planets[i].moon.col = colArray[i];
顺便说一句,我还建议更改您的代码以创建有关 once 的所有内容,然后将其分配到数组中:Planet
Planet planet = new Planet();
planet.distance = 100 + (i * 100);
planet.angle = 0 + (i * 20);
planet.diameter = 20 + (i * 10);
planet.col = colArray[i];
// etc
planets[i] = planet;
(我还建议使用私有字段,并且可能使用接受一堆值的构造函数,但这是另一回事。
评论