Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
116 views
in Technique[技术] by (71.8m points)

java - 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();. Please someone help me , thank you for your attention.

question from:https://stackoverflow.com/questions/65643187/why-am-i-getting-nosuchelementexception

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You have continueInput = false in the try block in such a way that it means that it will run regardless of the user input. This means the dowhile loop exits on the next try, and the input is closed. however, because this is in another while loop, it tries to get another input, even though the input scanner is closed! This gets you the NoSuchElementException.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...