How can I make the object array named rooms accessible to the static method at the end called retrieveRoom(); I tryed public static Rooms rooms[] = new Rooms[3]. But I am just getting errors from that. Any help is appreciated.
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];
}
}
Move
out of your
main()method, to the declarations section like thisThis will define a
roomsstatic member in yourMasterControlPanelclass.Here are some other tips:
Classexists. However, in order to access instance members (variables which belong to an instance of that class) you need an instance of the class.Rooms[] rooms = new Rooms[4];. Notice that array brackets are moved toTypepart, this will prevent confusion in future. “Let’s define An Array of Rooms with the name rooms“. This is not required however a good thing to do.roomsarray with the size of 3 however you are adding 4 elements to it. This will causeArrayIndexOutOfBoundsexception.privateto achieve Encapsulation. You can providepublicorprotectedmethods to retrieve thoseprivatemembers from out of your class.nelements, maximum number of consecutive iterations that you can make on that array is alsonthat’s for sure. That means in aforloop make sure that your loop condition isn-1for the last iteration. Remember, there is no4th element in a size4array.Here follows the code