Why? Because that is how the specification says it should behave; see @Sun's answer for the reference and the text from the spec.
And how can it overcome this?
Don't call close()
in a Scanner
that wraps System.in
. This is just an application of the general principle that a resource should be closed by the same code that opens it. (The JVM opens System.in
so you shouldn't close it.)
Alternatively if you must close the Scanner
, write or find a InputStream
wrapper class that ignores the close()
method and then use that to wrap System.in
.
By the way, it is a bad idea to instantiate new Scanner(System.in)
more than once. The problem is that a Scanner
may read any or all type-ahead. If you have two or more of them wrapping the same underlying stream, one Scanner
can capture input that a later one needs to read. This can lead to occasional unexpected behavior, and is likely to cause your application to fail if standard input is redirected ... at the shell level.