Evening all. I am a complete beginner to programming with Java, and I am learning about \"Scanner\", but when I type this basic code into Eclipse, I get a message saying \"R
This question is some months old but I would like to add: there is no reason to close System.in (which closing the Scanner will do) and you probably shouldn't. This is an automated warning Eclipse is giving related to Closeable and AutoCloseable and can be ignored if the underlying resource is System.in, System.out or System.err.
For any other resources, the 'correct' idiom has been shown (to ensure the resource gets closed even if exceptions are thrown).
Pre Java 7:
Scanner scanner = null;
try {
scanner = new Scanner(new FileInputStream("some/file"));
// statements that throw exceptions
} finally {
if(scanner != null)
scanner.close(); // also closes the FileInputStream
}
And post Java 7:
try(Scanner scanner = new Scanner(new FileInputStream("some/file"))) {
// statements that throw exceptions
}
See also "Why don't we close System.out Stream after using it?" The same is true for System.in: you shouldn't close a resource you did not open and the VM will handle it when the process terminates.