我想做一个模拟器,你可以进入房间然后离开。如果你离开了,你就在房间里,然后才进来。我想用递归和调用堆栈来实现它。如果我去一个新房间,效果会很好,但我不能回去了。有什么解决办法吗?
import java.util.Scanner;
public class Hausaufgabe10Aufgabe01 {
public static void main(String[] args) {
Room workingroom = new Room("Arbeitszimmer", false);
Room bedroom = new Room("Schlafzimmer", false);
Kitchen kitchen = new Kitchen("Kueche", false, false);
Bathroom bathroom = new Bathroom("Badezimmer", false, false);
Room hall = new Room("Flur", false);
hall.setNeighborRooms(bathroom, kitchen, bedroom, workingroom);
workingroom.setNeighborRooms(bedroom);
bedroom.setNeighborRooms(workingroom);
Flat myFlat = new Flat(bathroom, kitchen, bedroom, workingroom, hall);
boolean inFlat = false;
Scanner input = new Scanner(System.in);
walkThrough(myFlat, hall, input);
}
public static void walkThrough(Flat myFlat, Room myRoom, Scanner input) {
while (true) {
System.out.println("\nSie sind im: " + myRoom.getName());
System.out.println("Was wollen sie tun ? ");
System.out.println("1) Lichtsschalter bestätigen ? ");
System.out.println("2) Raum verlassen? ");
System.out.println("3) Nachbar Raum betreten ? ");
int intMax = 3;
if (myRoom.getName().equals("Kueche")) {
System.out.println("4) Herd betätigen ? ");
intMax = 4;
}
if (myRoom.getName().equals("Badezimmer")) {
System.out.println("4) Dusche betätigen ? ");
intMax = 4;
}
boolean shouldIReturn = false;
int choosenNumber = input.nextInt();
switch (choosenNumber) {
case 1:
myRoom.useLight();
break;
case 2:
shouldIReturn = true;
break;
case 3:
if (myRoom.getNeighborRooms() != null) {
myRoom = chooseRoom(input, myRoom);
walkThrough(myFlat, myRoom, input);
} else {
System.out.println("Keine Nachbarraum vorhanden");
}
break;
case 4:
if (intMax == 4) {
myRoom.useSpecial();
}
break;
default:
System.out.println("\nGeben sie eine richtige Eingabe ein!!");
if(intMax < 4) {
System.out.println("1 - 3 \n");
} else {
System.out.println("1 - 4 \n");
}
break;
}
if (shouldIReturn) {
return;
}
}
}
public static Room chooseRoom(Scanner input, Room myRoom) {
if (myRoom.getNeighborRooms().length > 0) {
for (int i = 0; i < myRoom.getNeighborRooms().length; ++i) {
System.out.println((i + 1) + ") "
+ myRoom.getNeighborRooms()[i].getName());
}
int choosenRoom = input.nextInt() - 1;
return myRoom.getNeighborRooms()[choosenRoom];
}
return myRoom.getNeighborRooms()[0];
}
}
我试图返回,所以我结束了当前的功能并返回到以前的功能,但我不知道我以前所在的房间的名称。我怎样才能得到我以前的东西?
2条答案
按热度按时间pvabu6sv1#
我的错是我覆盖了这里的旧参考:
我需要为递归创建一个新变量,如果不这样做,它将覆盖旧的变量
ego6inou2#
制造
myRoom
最后,看看你得到了什么编译时错误。想想以前发生的事情,你就会明白为什么打印时没有得到原来的房间名称
System.out.println("\nSie sind im: " + myRoom.getName());
.排队
myRoom = chooseRoom(input, myRoom);
您正在设置myRoom
一个新的价值观。所以当你从chooseRoom
.