I want to make a simulator where you can enter rooms and then leave them. If you leave you are in the room before you entered. I want to do it with recursion and call stack. It works good if I go into a new room, but I can't go back. Any solutions for this ?
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("
Sie 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("
Geben sie eine richtige Eingabe ein!!");
if(intMax < 4) {
System.out.println("1 - 3
");
} else {
System.out.println("1 - 4
");
}
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];
}
}
I tried to return so I end the current function and went back to the one before, but I do not get the name of the room I was in before. How can I get the object I was before ?
question from:
https://stackoverflow.com/questions/65647853/java-callstack-with-recursion-how-to-get-last-object-back 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…