Reputation: 1
So I am making a text based adventure game in JAVA at the moment. I am having a minor issue with my code, which is making the gameplay of the game very annoying. When the player inputs a command, like "go north", the first time it works fine. But the second time, it doesn't work. It doesn't display my default switch case, so it DOES recognize the command. When I enter the same command, for example, "go north", again, it works. So it doesn't work the first time, but just entering it one more time makes it work. Is there a way I can make it so it doesn't need two inputs for it to work? Here's my code:
//// USER INPUT TIME ////
System.out.println(">_");
playerCommand = input.nextLine();
loop: while (loopInt > 0) {
switch (input.nextLine()) {
case "go north":
case "n":
alleywayGoNorth();
break loop;
case "go south":
case "s":
alleywayGoSouth();
break loop;
case "open door":
case "o door":
alleywayOpenDoorLocked();
break loop;
default:
System.out.println("That command is not valid at the moment.");
break;
}
}
////////
Upvotes: 0
Views: 546
Reputation: 911
You are getting the input of the player two times. Once when you initialize the "playerCommand" and once when you create the switch statement. Remove the playerCommand initialization and replace it into the switch statement.
switch(playerCommand = input.nextLine()) {
...
}
If you do not still need the "playerCommand" variable, you can use:
switch(input.nextLine()) {
...
}
Upvotes: 0
Reputation: 3624
Your lines are "staggered" by one, because you retrieve the input twice.
Change:
switch (input.nextLine()) {
to
switch (playerCommand) {
Upvotes: 0
Reputation: 2793
The logic of your for loop is wrong. Change the switch (input.nextLine())
to switch (playerCommand)
and then add playerCommand = input.nextLine()
at the end of the switch statement. Also, remove all of references to your loop in your break statements.
Upvotes: 1