扫描仪使用后关闭 [英] Scanner close after use

查看:174
本文介绍了扫描仪使用后关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用如下所示的扫描器时:

While using scanner like following:

Scanner s = new Scanner(System.in);
String response = s.next();

Boolean approved = (response.contains("Y") || response.contains("y")) ? true : false;

if (approved){
  Do Stuff      
}
s.close();

我没有得到这样的Element异常异常:

I'm getting no such Element exception exception:

线程"main"中的异常java.util.NoSuchElementException在 java.util.Scanner.throwFor(未知源),网址为 java.util.Scanner.next(未知来源)****

Exception in thread "main" java.util.NoSuchElementException at java.util.Scanner.throwFor(Unknown Source) at java.util.Scanner.next(Unknown Source)****

我多次调用s(扫描仪),第二次调用时发生运行时错误. 这是由于关闭扫描仪,然后可能再次使用. 我的问题是 每次使用时,我都会创建一个新的Scanner实例,为什么会出现运行时错误?

I'm calling s (Scanner) multiple times, the runtime error occur on the second call. This is due to closing the scanner and than probably using it again. My question is, I'm creating a new instance of Scanner every time I'm using it so why I'm getting the runTime error?

推荐答案

问题是

关闭扫描器后,如果扫描器实现了Closeable接口,它将关闭其输入源.

When a Scanner is closed, it will close its input source if the source implements the Closeable interface.

http://docs.oracle. com/javase/1.5.0/docs/api/java/util/Scanner.html

因此scan.close()关闭System.in.

Thus scan.close() closes System.in.

要解决此问题,您可以

扫描器将静态扫描或每次通过扫描器对象进入方法并最后将其关闭.

Scanner scan static or pass every time scanner object in method and close it at last.

这篇关于扫描仪使用后关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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