Scanner报错java.util.NoSuchElementException

代码:

import java.util.Scanner;
public class Test_Scanner {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		String input = sc.next();
		sc.close();
		Scanner in = new Scanner(System.in);
		in.next();
	}
}

编译可以通过,但运行输入第一个数据后抛出异常。

问题:

Exception in thread "main" java.util.NoSuchElementException
	at java.util.Scanner.throwFor(Unknown Source)
	at java.util.Scanner.next(Unknown Source)
	at com.tulun.classandobject.Test_Scanner.main(Test_Scanner.java:12)

原因

源码:

  /**
     * Closes this scanner.
     *
     * <p> If this scanner has not yet been closed then if its underlying
     * {@linkplain java.lang.Readable readable} also implements the {@link
     * java.io.Closeable} interface then the readable's <tt>close</tt> method
     * will be invoked.  If this scanner is already closed then invoking this
     * method will have no effect.
     *
     * <p>Attempting to perform search operations after a scanner has
     * been closed will result in an {@link IllegalStateException}.
     *
     */
    public void close() {
        if (closed)
            return;
        if (source instanceof Closeable) {
            try {
                ((Closeable)source).close();
            } catch (IOException ioe) {
                lastException = ioe;
            }
        }
        sourceClosed = true;
        source = null;
        closed = true;
    }

 这样理解:创建的多个Scanner对象共用的是同一个输入流(System.in)。调用close()方法时,就关闭了System.in这个输入流。因此对于第二次创建的in来说,System.in已经被关闭了,就无法正常创建出对象,从而会产生java.util.NoSuchElementException异常。

解决方案:

在代码的最后再调用close()来关闭输入流。

参考资料

https://www.cnblogs.com/qingyibusi/p/5812725.html
https://blog.csdn.net/fashion_man/article/details/82973029

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值