对象数组的空指针异常 [英] Null pointer exception for Array of Objects
本文介绍了对象数组的空指针异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不熟悉使用对象数组,但无法弄清楚自己在做什么,为什么我总是收到Null指针异常.我正在尝试使用一组设置为打开或关闭的聚光灯对象来创建Theater类.但是-每当我在该数组上调用时,都会得到一个空指针异常.
I am new to using arrays of objects but can't figure out what I am doing wrong and why I keep getting a Null pointer exception. I am trying to create an Theatre class with an array of spotlight objects that are either set to on or off. But - whenever I call on this array I get a null pointer exception.
package theatreLights;
public class TheatreSpotlightApp {
public static void main(String[] args) {
Theatre theTheatre = new Theatre(8);
System.out.println("element 5 " + theTheatre.arrayOfSpotlights[5].toString());
}
}
package theatreLights;
public class Theatre {
spotlight[] arrayOfSpotlights;
public Theatre(int N){
arrayOfSpotlights = new spotlight[N];
for (int i = 0; i < arrayOfSpotlights.length; i++) {
arrayOfSpotlights[i].turnOn();
}
}
}
package theatreLights;
public class spotlight {
int state;
public spotlight(){
state = 0;
}
public void turnOn(){
state = 1;
}
void turnOff(){
state = 0;
}
public String toString(){
String stringState = "";
if(state == 0){
stringState = "is off";
}
else if(state==1){
stringState = "is on";
}
return stringState;
}
}
在创建数组时,我必须做一些基本的错误,但无法弄清楚.
I must be doing something basic wrong in creating the array but can't figure it out.
推荐答案
替换
arrayOfSpotlights[i].turnOn();
使用
arrayOfSpotLights[i] = new Spotlight();
arrayOfSpotlights[i].turnOn();
行
arrayOfSpotlights = new spotlight[N];
将创建一个聚光灯阵列.但是,它将不会使用聚光灯填充此阵列.
will create an array of spotlights. It will however not populate this array with spotlights.
这篇关于对象数组的空指针异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文