0

I have the following example code showing two scanner instances the first gets some input from the user then closes. A second instance is created later in the program and causes an Exception in thread "main" java.util.NoSuchElementException

I understand the Exception is created when you try to use a closed instance. What I don't understand is how to open a second instance later without getting an error. I could leave the instance open but if its not being used for a while should it not be closed?

I would like to reopen the first instance but have been unable. So I tried creating a second instance but the second instance creates and Exception if the first instance has been closed.

Getting to the point. How can you get user input without leaving the Scannner instance open between .next(); calls?

Why does calling sc2.next(); cause an Exception after the first sc instance is closed? They are different instances.

What is the correct way to get user input a second time after closing a instance?

public class Main {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        System.out.println("Enter String");
        sc.next();
        sc.close();

        /*
         * Do some other stuff and then get more input later in the program
         * */

        Scanner sc2 = new Scanner(System.in);
        System.out.println("Enter Second String");
        sc2.next();
        sc2.close();
    }
}

And here is the compiler output

Enter String
test
Enter Second String
Exception in thread "main" java.util.NoSuchElementException
    at java.base/java.util.Scanner.throwFor(Scanner.java:937)
    at java.base/java.util.Scanner.next(Scanner.java:1478)
    at com.company.Main.main(Main.java:22)

Process finished with exit code 1
  • `System.in` is a **global**. Closing a `Scanner` closes the resources associated with it. In this case `System.in`. **Remove** `sc.close();` – Elliott Frisch Mar 20 '22 at 21:47

0 Answers0