Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scanner - java.util.NoSuchElementException

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();
    }
like image 745
Alan Avatar asked Dec 23 '13 08:12

Alan


1 Answers

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.

like image 105
Maroun Avatar answered Oct 20 '22 18:10

Maroun