After finishing using the scanner
, you must close with the close
method:
scanner.close();
The reason why you must close it is because the Scanner
class implements the Closeable interface. Straight from the 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).
Essentially, if you never close the Scanner
, then the program will continue to seek for input and keep hold of resources. Here is a really 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();
}
}
Read more about Scanner
from the API.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…