Scanner - java.util.NoSuchElementException

Alan picture Alan · Dec 23, 2013 · Viewed 13k times · Source

Does anyone see a problem with this? First input works fine, but after the first loop, it doesn't ask to enter a value again. How do I fix this?

    int value;
    while(true)
    {
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter a value");
        try 
        {
            value = scan.nextInt();
            System.out.println("value provided is: " + value);
            scan.nextLine(); // consumes "\n" character in buffer
        }
        catch(InputMismatchException e) // outputs error message if value provided is not an integer
        {
            System.out.println("Incorrect input type. Try again.");
            continue; // restarts while loop to allow for re-entering of a valid input
        }
        scan.close();
    }

Answer

Maroun picture Maroun · Dec 23, 2013

Move scan.close(); to outside the while loop.

Also you don't have to construct a new Scanner on each iteration. Move the declaration to outside the loop as well.


When close the Scanner, this closes the System.in input stream.

So now when you try to instantiate it again, it doesn't find any opened stream and you'll get that exception.