Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
486 views
in Technique[技术] by (71.8m points)

java.util.scanner - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...