我正在制作一个基于文本的冒险“游戏”来进行练习,(我意识到这可能是正确的方法),我希望用户能够输入“命令”来查看他当前可以执行哪些命令使用 - 如果他们已经知道命令,我希望他们能够只输入命令本身(在本例中为 1、2 或 3)。然而,我遇到的问题是,如果用户输入“命令”,他们之后将无法使用它们(1,2 或 3)。我知道我可以使用另一台扫描仪,但我试图在这里避免这种情况。
out.print("\nWhat do you want to do? *Type 'Commands' to look through your options.*\n");
String playerInput = userInput.nextLine();
if (playerInput.equals("Commands")){
out.println("\nCommands\n"
+ "(1) - Inspect\n"
+ "(2) - Explore\n"
+ "(3) - Inventory\n");
}
if (playerInput.equals("1")) {
out.print("You find a box under your bed. \nDo you want to open it? (Y/N)\n");
String playerAnswer = userAnswer.nextLine();
if (playerAnswer.equals("Y")) {
out.println("Inside the box you find a photograph");
}
// Another if statement with option 2 here
}
最佳答案
循环直到满足某些退出条件。请注意,每次调用 userInput.nextLine()
时,它都会等待用户输入新的文本行并将其分配给 playerInput
,然后再继续。
String playerInput = "";
out.print("\nWhat do you want to do? *Type 'Commands' to look through your options.*\n");
while(! playerInput.equals("Exit")){
playerInput = userInput.nextLine();
if (playerInput.equals("Commands")){
out.println("\nCommands\n"
+ "(1) - Inspect\n"
+ "(2) - Explore\n"
+ "(3) - Inventory\n"
+ "Exit - Quits the game\n");
}
if (playerInput.equals("1")) {
out.print("You find a box under your bed. \nDo you want to open it? (Y/N)\n");
String playerAnswer = userAnswer.nextLine();
if (playerAnswer.equals("Y")) {
out.println("Inside the box you find a photograph");
}
//More if statements...
}
关于java - 如果写入某个命令,如何跳过 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28034704/