You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何Java菜单程序返回主菜单时抛出NoSuchElementException异常?

解决Scanner的NoSuchElementException:菜单返回后输入报错

这个问题的核心是你错误的Scanner关闭时机!

看你的代码,input.close()被写在了外层while循环的末尾——这意味着不管你选的是1/2/3(操作后返回菜单)还是0(退出程序),每完成一次菜单选择的do-while循环,都会直接关闭Scanner。而Scanner关闭时会连带关闭它关联的标准输入流System.in,这个流一旦关闭就无法重新打开,所以当你完成操作回到菜单,再次调用input.nextInt()时,就会因为输入流已经失效而抛出NoSuchElementException。

修复步骤:

  • 把input.close()移到外层while循环的外面,等整个菜单逻辑完全结束(用户选择0退出,menuExit变为false后),再执行关闭操作。
  • 保留你捕获InputMismatchException后的input.nextLine()——这一步很重要,它会清空缓冲区里的无效输入(比如用户输了字母),避免后续一直触发异常死循环。

修改后的完整代码示例:

while (menuExit == true) { 
    System.out.println(SEPARATE_LINE); 
    System.out.println("Which do you want to do ? "); 
    System.out.println(SEPARATE_LINE); 
    System.out.println("1.Register"); 
    System.out.println("2.Sign in"); 
    System.out.println("3.Check shop status"); 
    System.out.println("0.Exit"); 
    System.out.println(SEPARATE_LINE); 
    System.out.print("Please enter your choice as number:"); 
    
    do{ 
        try{ 
            int selectMain = input.nextInt(); 
            if(selectMain == 1){
                register(currentNum , customers); 
                customers.clear(); 
                customers = ReadData.readCustomerData(); 
            }else if(selectMain == 2){
                signIn(customers,historys,cusData,hisData); 
            }else if(selectMain == 3){
                CheckData.checkShopStatus(shops,shopData); 
            }else if(selectMain == 0){
                System.out.println("Thank you"); 
                menuExit = false; 
            }else { 
                System.out.println("Your input are wrong , Please enter again."); 
            } 
            continueInput = false; 
        }catch(InputMismatchException ex){ 
            System.out.println("Please enter again."); 
            input.nextLine(); 
        } 
    }while (continueInput); 
}
// 仅在所有菜单操作完成后关闭Scanner
input.close();

简单来说:不要在循环内部关闭Scanner,要等所有需要输入的逻辑彻底结束后再执行关闭,因为底层的系统输入流无法重复打开复用。

内容的提问来源于stack exchange,提问作者Wei Jun Tee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 11:22:41