如果写入某个命令,如何跳过if语句

时间:2015-01-19 22:36:55

标签: java if-statement java.util.scanner

我正在为练习做一个基于文本的冒险“游戏”,(我意识到这可能是正确的方法)并且我希望用户能够输入'Command'以查看他当前可以执行的命令使用 - 如果他们已经知道命令,我希望他们能够只输入命令本身(在这种情况下是1,2或3)。但是,我遇到的问题是如果用户输入'Command',他们将无法使用它们(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
}

1 个答案:

答案 0 :(得分:3)

循环直到满足某些退出条件。请注意,每次调用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...
}