如何使CTRL + Z不要搞乱java控制台程序

时间:2018-04-05 07:37:45

标签: java eclipse console eof nosuchelementexception

我的最终项目要求之一是,如果它是基于控制台的我的,输入 ctrl + z WON'搞乱程序。我的扫描程序中的nextLine()语句在while循环中,当我尝试从输入 ctrl + z 中捕获NoSuchElementException时,catch块中的错误消息循环无休止。

        while (!advanceTurn) {

        System.out.print("\nCommand: ");

        try {input = s.nextLine();}
        catch (NoSuchElementException e) {

            System.out.println("Use the EXIT command to exit the game.");
            s = new Scanner(System.in);
            input = "asdfjkl;";
            continue;

        }

        System.out.println();

        // This takes the input and decides what command was entered (if any) and deals
        // with it appropriately.
        parseCommand(input);

    }

正如您在代码中看到的那样,我已经尝试在捕获错误时重新初始化扫描程序,然后跳回到循环的开头,以便可以抓取新行,但它会出现即使没有来自键盘的新输入,错误仍然存​​在,所以我对如何解决这个问题感到非常难过。感谢任何帮助。谢谢。

编辑:如果有帮助的话,我正在使用Eclipse IDE。

1 个答案:

答案 0 :(得分:1)

我今天和我的讲师谈过,我们通过在catch块中使用return语句跳转到while循环之外,然后在再次进入循环之前将s初始化为新的扫描程序来解决问题。由于此片段的目的是重复获取命令,直到输入构成转弯结束的某些命令,因此每次输入命令时都会输入while循环,现在它对我来说效果很好。