[英]Mutator methods with an Array of Objects in Java
So i have an array of Room objects, the reason its static is because I'm doing it in main. 所以我有一个Room对象数组,其静态的原因是因为我在main中进行处理。
private static Room[] rooms = new Room[6];
So in my room class, i have a method called setStatus which sets a string to the room object 所以在我的房间类中,我有一个名为setStatus的方法,该方法将一个字符串设置为room对象
public String setStatus(String answer) {
if (answer.equalsIgnoreCase("Available") || answer.equalsIgnoreCase("Occupied")
|| answer.equalsIgnoreCase("Needs cleaning (unavailable)")
|| answer.equalsIgnoreCase("For walk-ins")
|| answer.equalsIgnoreCase("For emergencies")) {
this.status = answer;
return status;
} else {
System.out.println("Status must be set to Available, Occupied or Needs cleaning (unavailable)");
return null;
}
}//end of setStatus
Now i want to set the status for each position in the array 现在我想设置数组中每个位置的状态
rooms[random.nextInt(6)].setStatus("For walk-ins");
However i get a nullpointer exception when i set the status of the array, any ideas?. 但是,当我设置数组的状态时,出现空指针异常,有什么想法吗?
the reason [
rooms
] static is because I'm doing it in main.[
rooms
]静态的原因是因为我主要在这样做。
This is not your only choice - you could have declared it as a local variable inside the main
method. 这不是您唯一的选择-您可以在
main
方法中将其声明为局部变量。
However i get a null pointer exception
但是我得到一个空指针异常
This is because you have initialized the array object, but you have forgotten to initialize its individual elements. 这是因为您已经初始化了数组对象,但是却忘记了初始化其各个元素。 You need to add a loop, and create each room individually.
您需要添加一个循环,并分别创建每个房间。
If you keep rooms
static, add a static initialization block, like this: 如果让
rooms
保持静态,请添加一个静态初始化块,如下所示:
static {
for (int i = 0 ; i != rooms.length ; i++) {
rooms[i] = new Room(); // You may need to pass other parameters to the constructor
}
}
If you prefer to change rooms
to a local variable, you can put the for
loop in your main
, immediately after the declaration / initialization of the rooms
array object. 如果您希望将
rooms
更改为局部变量,则可以在声明/初始化rooms
数组对象之后,将for
循环放入main
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.