我正在使用两个独立的类,Animal
和 Room
。 Room
是用一个数组实例化的。 Animal
对象随后被实例化并放置在 Room
中的数组中。我如何才能为 Animal
对象提供对它们所在的 Room
的引用,以便当我对它们调用 look()
方法时,它们可以返回他们所在房间的名称吗?
public static void main(String[] args) {
Room mainRoom = new Room("The Lobby");
Animal gizmo = new Animal("Gizmo");
mainRoom.addAnimal(gizmo);
System.out.println(mainRoom.toString());
gizmo.look();
}
-
public class Room {
private String name;
private Animal[] animals;
private Room currentRoom;
int i = 0;
public Room(String name) {
setName(name);
animals = new Animal[10];
}
public String toString() {
String temp = new String();
temp += "\nThis room is " + name + ".\n\n";
temp += "In the lobby are the following animals: \n";
for (Animal s : animals) {
temp += s.toString() + "\n";
}
return temp;
}
public void setName(String name) {
this.name = name;
}
public void addAnimal(Animal a) {
if (i < 10) {
if (animals[i] != null) {
i++;
addAnimal(a);
} else {
animals[i] = a;
}
} else {
System.out.println("Room full");
}
}
}
-
public class Animal {
private Room currentRoom;
private String name;
public Animal() {
}
public Animal(String name) {
setName(name);
}
public void setName(String name) {
this.name = name;
}
public String toString() {
return "\t" + name;
}
public void look() {
System.out.println(name + " is currently in " + getCurrentRoom());
//getCurrentRoom().toString();
}
public Room getCurrentRoom() {
return this.currentRoom;
}
public void setCurrentRoom(Room currentRoom) {
this.currentRoom = currentRoom;
}
}
最佳答案
How can I give the Animal objects a reference to what Room they are placed into so when I call a look() method on them, they can return the name of the Room they are in?
您应该在 Animal 中设置房间:
Animal gizmo = new Animal("Gizmo");
gizmo.setCurrentRoom(mainRoom); // this would set mainRoom as the attribute of gizmo
在此处进一步说明您的代码:
public void look() {
System.out.println(name + " is currently in " + getCurrentRoom());
//getCurrentRoom().toString();
}
将获取上面代码设置的 currentRoom
。
关于java - 如何通过引用让一个Animal对象知道它在哪个Room,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46024537/