Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot use multiple Scanner objects in Java

I have started learning Java recently. I was learning to take user input using Scanner class when I Started getting an error. Here is the code:

Scanner userInput1 = new Scanner(System.in);
        String name = userInput1.nextLine();
        System.out.println("Hi "+ name);
        userInput1.close();

        Scanner userInput2 = new Scanner(System.in);
        int age = userInput2.nextInt();
        System.out.println(age);

I get the following error when I enter "Deadboy" as input:

Hi Deadboy
Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:862)
    at java.util.Scanner.next(Scanner.java:1485)
    at java.util.Scanner.nextInt(Scanner.java:2117)
    at java.util.Scanner.nextInt(Scanner.java:2076)
    at com.first.Main.main(Main.java:17)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)

Process finished with exit code 1

I am unable to enter the value for "age". If, however, I comment the line "userInput1.close()", the code works.

What is the problem?

I am sorry if this question has been answered before. I found a similar question but I was not sure if its answers were the ones I was looking for.

like image 976
Rajat Avatar asked Sep 21 '26 01:09

Rajat


2 Answers

There's a couple of problems here.

First, you do not want to close the System.in stream. Other parts of the program may be using it, and you don't want to interfere with their normal operation.

Second, there's no benefit to creating more than one Scanner object. It's simply reading input from a stream, and having more than one reference to that stream isn't necessary or beneficial to your operations.

To that end, the fix to this would be straightforward:

  • Use only one instance of the Scanner attached to System.in, and
  • Remove the close() method call.
like image 99
Makoto Avatar answered Sep 23 '26 13:09

Makoto


The problem here is that when you are closing Scanner userInput1, it closes input source, with which it was created - in this case it is InputStream you got from accessing System.in. So when you call

Scanner userInput2 = new Scanner(System.in);

at this point System.in InputStream is already closed, and you can not longer work with it.

like image 20
Vladislav Lezhnin Avatar answered Sep 23 '26 15:09

Vladislav Lezhnin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!