在循环中读取键盘输入

时间:2015-10-10 11:15:32

标签: java input while-loop nosuchelementexception

我试图做一个简单的菜单系统,但它给了我一个" NoSuchElementException"。

当我按下选项1时,它执行得很好,但当我拨打选项2时,它会要求我提供" w"然后抛出异常。

我已尝试添加if (sc.hasNext),就像我在post上看到的那样,但在我调用选项2之后,它会保持循环并且不允许我为X键入值

    public Main() {
    int x = 5;
    Scanner sc = new Scanner(System.in);

    while(x != 0) {
        System.out.println("########## MT ###########");
        System.out.println("# 1 - Read MT           #");
        System.out.println("# 2 - Read w            #");
        System.out.println("# 0 - Exit              #");
        System.out.println("#########################");
        System.out.print("Option: ");

        x = sc.nextInt(); //Here is the error.

        switch (x) {
        case 1:
                setMaquina(new MT());
            break;
        case 2:
                if (getMaquina() == null) {
                    System.out.println("MT is null.");
                }
                else {
                    Scanner scc = new Scanner(System.in);
                    System.out.print("    ~ w: ");

                    String w = scc.nextLine();

                    getMaquina().readString(w);

                    scc.close();
                }
            break;
        case 0:
            x = 0;
            break;
        default:
            break;
        }
    }

    sc.close();
}

修改

Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:862)
    at java.util.Scanner.next(Scanner.java:1485)
    at java.util.Scanner.nextInt(Scanner.java:2117)
    at java.util.Scanner.nextInt(Scanner.java:2076)
    at maquina.turing.Main.<init>(Main.java:26)
    at maquina.turing.Main.main(Main.java:11)

0 个答案:

没有答案