Search code examples
javajava.util.scannernosuchelementexceptionsystem.in

Issue with java Scanner not taking nextLine on new instance


package sandbox2;

import java.util.Scanner;

public class Sandbox2
{
    public static void main(String[] args)
    {
        for (int i = 0; i < 5; i++)
        {
            String s = askForProperty("Enter value for " + i + ": ");
            System.out.println(i + " is: " + s);
        }

    }

    private static String askForProperty(String message)
    {
        Scanner keyboard = new Scanner(System.in);
        System.out.print(message);
        String s = keyboard.nextLine();
        keyboard.close();

        return s;
    }
}

When i run the above code, it returns the first response PERFECTLY. When it tries to ask for the second response, it returns:

java.util.NoSuchElementException: No line found

Why would it return this error? Each time the method askForProperty is called, the Scanner is a completely new instance! Does it have something to do with System.in as an input stream?


Solution

  • Define your scanner as a class variable and then close it only after you are done with all iterations. In your current setup, when you call keyboard.close you are also closing System.in which makes it unusable later on.

    package sandbox2;
    import java.util.Scanner;
    
    public class Sandbox2 {
        static Scanner keyboard = new Scanner(System.in); // One instance, available to all methods
    
        public static void main(String[] args)  {
            for (int i = 0; i < 5; i++) {
                String s = askForProperty("Enter value for " + i + ": ");
                System.out.println(i + " is: " + s);
            }
            keyboard.close(); //Only close after everything is done.
        }
    
        private static String askForProperty(String message) {
            System.out.print(message);
            String s = keyboard.nextLine();
            return s;
        }
    }