Java Scanner.nextLine() not waiting for input

前端 未结 2 699
醉话见心
醉话见心 2020-12-07 03:06

I have several methods that I\'ve used previously to accept user input and return it as a certain data type to the method that calls for it. I have used these methods, or v

相关标签:
2条回答
  • 2020-12-07 03:44

    As I stated in my comment, the problem is that you're closing System.in each time you do something like this:

    Scanner scan = new Scanner(System.in);
    ...
    scan.close();
    

    Now, look at the specification of Scanner.nextLine

    Throws:

    • NoSuchElementException - if no line was found
    • IllegalStateException - if this scanner is closed

    Now, since the scanner itself is not closed, an IllegalStateException will not be thrown. Instead, as you mentioned before, the other exception, "typically related to not finding a new line", -- NoSuchElementException -- is thrown.

    Presuming this you're using JDK 7, you can see how this works by examining Scanner.throwFor:

    if ((sourceClosed) && (position == buf.limit()))
        throw new NoSuchElementException();
    

    Since your exception is thrown, a value of 0 is returned by getUserChar, which is then used in the run loop:

        do {
            userInput = mainMenu();
            if (isUserInputValid(userInput)) {
                ...
            } else {
                System.out.println("\nMainMenu");
            }
        } while (!wantToQuit);
    

    Since the input is invalid, you're caught in a loop printing "\nMainMenu\n".

    To correct the issue, try to use a single Scanner and don't close System.in ;-)

    0 讨论(0)
  • 2020-12-07 03:50

    Please don't close the Scanner.

    scan.close();    // Don't do it.
    

    Doing that is causing the problem.

    0 讨论(0)
提交回复
热议问题