无法在Java中使用多个Scanner对象 [英] Cannot use multiple Scanner objects in Java

查看:78
本文介绍了无法在Java中使用多个Scanner对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始学习Java.开始出现错误时,我正在学习使用Scanner类进行用户输入.这是代码:

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);

当我输入"Deadboy"作为输入时,出现以下错误:

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

我无法输入年龄"的值. 但是,如果我注释"userInput1.close()"行,则该代码有效.

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

出什么问题了?

很抱歉,如果您之前已经回答了这个问题.我发现了一个类似的问题,但是我不确定它的答案是否正是我所寻找的.

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.

推荐答案

这里有两个问题.

首先,您不是要关闭System.in流.该程序的其他部分可能正在使用它,并且您不想干扰它们的正常运行.

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.

第二,创建多个Scanner对象没有任何好处.它只是从流中读取输入,并且对该流没有多个引用对您的操作是不必要的或无益的.

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:

  • 仅使用连接到System.in的扫描仪的一个实例,并且
  • 删除close()方法调用.
  • Use only one instance of the Scanner attached to System.in, and
  • Remove the close() method call.

这篇关于无法在Java中使用多个Scanner对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆