简体   繁体   English

为什么我会收到 NoSuchElementException?

[英]Why am I getting NoSuchElementException?

Here is my code:这是我的代码:

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);
    input.close();

This is the menu of my program, when I enter into one of these selection and come back to the menu, I got NoSuchElementException, the error point to the line int selectMain = input.nextInt();.这是我程序的菜单,当我进入这些选择之一并返回菜单时,我得到了 NoSuchElementException,错误指向 int selectMain = input.nextInt(); 行。 Please someone help me, thank you for your attention.请有人帮助我,谢谢您的关注。

You have continueInput = false in the try block in such a way that it means that it will run regardless of the user input.您在 try 块中有 continueInput = false ,这意味着无论用户输入如何,它都会运行。 This means the dowhile loop exits on the next try, and the input is closed.这意味着 dowhile 循环在下一次尝试时退出,并且输入被关闭。 however, because this is in another while loop, it tries to get another input, even though the input scanner is closed.但是,因为这是在另一个 while 循环中,所以它会尝试获取另一个输入,即使输入扫描器已关闭。 This gets you the NoSuchElementException.这会让你得到 NoSuchElementException。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM