java中的NoElementException

问题描述 投票:-2回答:1
int selection;
    while (true) {
        selection = printing();
        if (selection == 4) {

            id = starting();

            if (id < 1 || id > 10) {
                if (id == -20150901) {
                    System.out.println("Exit code entered");
                    break;
                }

                id = incorrectId(id);
            }
        }


    }


public static int printing(){
    Scanner sc = new Scanner(System.in);
    System.out.print("Main menu\n1: check balance\n2: withdraw\n3: deposit\n4: exit\nEnter a choice: ");
    System.out.print("Enter a choice: ");
    int selection = sc.nextInt();
    return selection;
}

这是我的java代码的一部分。 NoElementException出现在第三行。如果需要整个代码,我将在此复制并粘贴并解释它的含义。我怎样才能解决这个异常?我想在每次循环开始时获得键盘输入。

谢谢。

java exception java.util.scanner
1个回答
0
投票

每次调用System.in时,您的代码都会创建一个包装printing()的新Scanner。这是不正确的。相反,你的应用程序应该创建一个Scanner包装System.in,保存在某个地方,并重复使用每个printing()调用和所有其他你从System.in阅读的地方。

创建多个Scanner对象的问题在于,hashNext*next*方法可以使字符在扫描仪的缓冲区中“预读”字符。所以第一个printing()可以“消耗”所有角色。


现在这可能不是您问题的真正原因。其他可能的原因可能是:

  • 标准输入可以为空,或
  • 您可能(直接或间接)在代码的其他部分关闭System.in

但是,我发现的问题是在其他环境中导致应用程序失败的错误......并且建议理解并修复它。

© www.soinside.com 2019 - 2024. All rights reserved.