程序误读了我的输入

Program is misreading my input

所以。我正在做一个关于 java 的教程并尝试制作一个 D&D 角色 sheet 保护程序。我遇到的问题并不严重,但在我命令它加载后,它会按预期执行消息,但是当我输入 'new' 并按回车键时,它会等到我再次按回车键,然后它为 "new" 执行我的 else 代码而不是我的 if。我最终不得不再次输入它。

do {
        if (command.equalsIgnoreCase("new")) {
            System.out.println("Let's create a character!\n");

然后是一堆无关紧要的其他代码然后:

    // LOAD CHARACTER
        else if (command.equalsIgnoreCase("load")) {
            // placeholder for load char.
            System.out
                    .println("This is where we will load a character in the     future.  For now it is empty, please select new.");
            command = text.nextLine();
            // EXIT CODE
        } else if (command.equalsIgnoreCase("exit")) {
            System.exit(0);

            // Invalid Response
        } else
            System.out.println("Invalid response. Please try again. ");
        command = text.nextLine();
    } while (!command.equalsIgnoreCase("exit"));

结果如下:

请说 'New' 获取新角色或 'Load' 加载以前保存的角色...
加载
这是我们将来加载角色的地方。目前为空,请select新建。
新建

无效响应。请再试一遍。
new
让我们创建一个角色!

这个角色的名字是什么?

您的 'load' if 部分和循环末尾都有 command = text.nextLine();。第一个输入是在 if 块中获取的,然后读取空白行,并在下一轮的 if/else 流中进行比较。

将输入读数放在 if-else 链之外是更好的方法,因为您在每个 else 块中都没有重复代码。

do {
    if (command.equalsIgnoreCase("new")) {/*do new stuff*/} 
    else if (command.equalsIgnoreCase("load")) {/*do load stuff*/}
    else if (command.equalsIgnoreCase("exit")) {/*do exit stuff*/}
    else {/*do default/bad input stuff*/}

    //This line runs every loop iteration(unless one of your if blocks calls break or exit
    command = text.nextLine();
} while (!command.equalsIgnoreCase("exit"));

打印 This is where we will load ... 后,您在再次检查输入之前读取了两次输入。一次紧接在消息之后,一次在循环结束时。