我正在创建一个名为rooms的对象数组。
static Room [] rooms = new Room [3];
//populate the array.
rooms[0] = new Room ("Bedroom", "This is your bedroom." );
rooms[1] = new Room("Hallway", "This is the hallway of your house.");
//constructor
static String room = "";
static String descriptionOfTheRoom = "";
public Room ( String newRoom, String newDescriptionOfTheRoom ){
room = newRoom;
descriptionOfTheRoom = newDescriptionOfTheRoom;
}
// get room method
public String getRoom (){
return room;
}
// when I try to get the room.
System.out.println("Room" + r[i].getRoom() );
它打印出最后添加到数组的房间。所以总是打印走廊。 那么我怎样才能打印出每个元素呢?或访问每个元素?
提前感谢大家。
答案 0 :(得分:1)
这是因为您制作了descriptionOfTheRoom
和room
变量static
。它们应该是实例变量。
与实例变量不同,static
成员在类的所有实例之间共享。这些成员几乎从不在构造函数中设置(有时您可能需要修改它们,但这并不常见)。
您应该生成room
和descriptionOfTheRoom
个实例变量,即每Room
个对象一个。删除static
将解决此问题。