使用完扫描仪后,必须使用close方法关闭:
scanner.close();
您必须关闭它的原因是因为Scanner类实现了Closeable接口.直接来自API:
A Closeable is a source or destination of data that can be closed. The
close method is invoked to release resources that the object is
holding (such as open files).
基本上,如果您从未关闭扫描仪,那么程序将继续寻求输入并保持资源.这是一个真正的simple example:
Scanner scanner = null;
try {
scanner = new Scanner(System.in);
while (scanner.hasNext()) {
System.out.println(scanner.next());
//do whatever you need here
}
} finally {
if (scanner != null) {
scanner.close();
}
}
从API了解有关Scanner的更多信息.