我怎样才能使名为rooms的对象数组在最后被称为restoreRoom()的静态方法访问;我尝试了公共静态Rooms rooms [] = new Rooms [3]。但是我只是从中得到错误。任何帮助表示赞赏。
public class MasterControlPanel{
public static void main(String[] args){
Rooms rooms[] = new Rooms[3];
rooms[0] = new Rooms("Room U", 1, 4, 4);
rooms[1] = new Rooms("Room U", 2, 4, 4);
rooms[2] = new Rooms("Connector X", 3, 2, 4);
rooms[3] = new Rooms("Connector U", 4, 2, 4);
for(int x = 0; x <= rooms.length; x++){
rooms[x].createLights();
rooms[x].createWalls();
}
}
public static Object retrieveRoom(int connectedRoom){
connectedRoom -= 1;
return rooms[connectedRoom];
}
}
最佳答案
移动
public static Rooms[] rooms = new Rooms[4];
从您的
main()
方法中移到这样的声明部分public class MasterControlPanel {
public static Rooms[] rooms = new Rooms[4];
public static void main(String[] args) {
...
}
}
这将在您的
rooms
类中定义一个MasterControlPanel
静态成员。以下是其他一些技巧:
只要存在
Class
,就可以访问静态成员。但是,为了访问实例成员(属于该类的实例的变量),您需要该类的实例。使用
Rooms[] rooms = new Rooms[4];
。请注意,将数组括号移到Type
部分,这将防止将来出现混淆。 “让我们用房间名称来定义一个房间数组”。但这不是必需的,但要做的一件好事。您正在定义大小为3的
rooms
数组,但是要向其中添加4个元素。这将导致ArrayIndexOutOfBounds
异常。您应该使您的成员
private
达到Encapsulation。您可以提供public
或protected
方法来从类之外检索那些private
成员。当一个数组包含
n
个元素时,可以确定对该数组进行的连续迭代的最大次数也是n
。这意味着在for
循环中,确保最后一次迭代的循环条件为n-1
。请记住,大小为4
的数组中没有第4
个元素。下面是代码
public class MasterControlPanel {
public static Room[] rooms = new Room[4];
public static void main(String[] args) {
rooms[0] = new Room("Room U", 1, 4, 4);
rooms[1] = new Room("Room U", 2, 4, 4);
rooms[2] = new Room("Connector X", 3, 2, 4);
rooms[3] = new Room("Connector U", 4, 2, 4);
for (int x = 0; x <= rooms.length-1; x++) {
rooms[x].createLights();
rooms[x].createWalls();
}
}
public static Room retrieveRoom(int connectedRoom) {
connectedRoom -= 1;
return rooms[connectedRoom];
}
}
class Room {
// These are instance members for Room class
private String roomString;
private int roomInteger1, roomInteger2, roomInteger3;
public Room(String string, int integer1, int integer2, int integer3) {
// This is the constructor for Room object
this.roomString = string;
this.roomInteger1 = integer1;
this.roomInteger2 = integer2;
this.roomInteger3 = integer3;
}
public void createLights() {
// This method creates lights
}
public void createWalls() {
// This method creates walls
}
// These are Getters and Setters for Room members
public String getRoomString() {
return roomString;
}
public void setRoomString(String roomString) {
this.roomString = roomString;
}
public int getRoomInteger1() {
return roomInteger1;
}
public void setRoomInteger1(int roomInteger1) {
this.roomInteger1 = roomInteger1;
}
public int getRoomInteger2() {
return roomInteger2;
}
public void setRoomInteger2(int roomInteger2) {
this.roomInteger2 = roomInteger2;
}
public int getRoomInteger3() {
return roomInteger3;
}
public void setRoomInteger3(int roomInteger3) {
this.roomInteger3 = roomInteger3;
}
}
关于java - Java访问实例变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9559070/