Java Scanner class and Standard In Troubles

I ran into a bit of trouble today with the Java Scanner class that I thought was worth mentioning. Personally I really like the Java Scanner class because it is a great way to easily read from standard input (stdin). In specific the issue I had was that I noticed the Scanner class allows you to close stdin. This is the part I found problematic. Consider the following code from

import java.util.Scanner;
public class Test
    public static void main(String args[])
     Scanner scanner = new Scanner(;

     System.out.print("Enter a number: ");
     System.out.println("Your number was: " + scanner.nextInt());


     scanner = new Scanner(;

         System.out.println("Whoops! nothing to read!");

     System.out.println("Things seemed to  have worked correctly.");

When you run this code what you will notice is that after you enter the first number the program goes straight into that if statement. This is not what we might expect however because the has<something> functions are supposed to hang until something is typed.

The reason for this is the call to scanner.close() which ends up closing standard in. To be honest I’m not sure how this would work on a Windows system, but I know it was a bit of a problem for me on my Linux box. The simple fix is to just not call .close() , but since it is normally good practice to close things you opened I didn’t think much of it when I first wrote the code. I guess we didn’t technically open stdin, so perhaps that is the correct way to look at it .

At any rate I wouldn’t call this a bug of Scanner, but simply something to look out for when using the Scanner class.

Happy coding 🙂 !


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: