代码:
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