Yesterday I gave my students a warm up exercise in my third year Java course. The students were free to use console, Swing or JavaFX for user input. Most chose console because they had minimal exposure to GUI coding and that is one of the main topics in my course. Within a few minutes some hands went up in regards to the use of the Scanner class. Here is a simplified version of what they were trying to do.
When this program executes it asks for the first String but never asks for the int. A run looks like:
It never stops to ask for the number and immediately prints out the default value for num. I had never seen this problem before. When I teach an introductory course I show my students that the Scanner for keyboard input should, in most cases, be a class variable initialized in the constructor. I also must admit that I never close the Scanner object when the keyboard is involved.
You can see that in the code the Scanner object is closed in each method. I didn’t think this was a problem and so I stared at the student’s code for a few minutes and then went to Google. There was not much to be found. Most of the information showed that when using Scanner to access a file you should close it. Most articles that used Scanner for keyboard input declared the Scanner in a method and closed it at the end of the method. There was one suggestion in a StackOverflow posting that suggested a potential problem with closing Scanner for keyboard input but it was not definitive.
My next experiment was to remove the close() statements. The Scanner performed as originally expected:
So, back to research on Google where I uncovered a fact not mentioned in any JavaDocs or in any article from any source when discussing the Scanner class. If System.in, a BufferedInputStream from the keyboard, is closed, as happens when the Scanner object is closed, you are closing a System stream that cannot be re-opened. The program must be exited and then re-run to re-establish System.in.
I thought this was strange and looked deeper into how the keyboard was connected to System.in. This stream is established by private methods in the JVM. I did see suggestions as to how this could be re-established but I suspect that this code may have never been tested:
Neither worked to re-establish the connection between System.in and the keyboard. If you know a way then I’d dearly like to know. For now:
DO NOT CLOSE A SCANNER OBJECT INITIALIZED WITH System.in !