Reading User Input Using the Scanner Class in Java

Java is very versatile in its ability, but can become even more versatile with the integration of user input. One way to have user input is the Scanner Class. This class allows the programmer to scan the keyboard and get input from the user.

How to Instantiate the Scanner Class

Since it is not built into the regular Java library, it needs to be imported. It can be imported like so:

Scanner Class import

or

Screen Shot 2016-03-01 at 1.04.58 PM

Note: All imports are declared at the top of the program before the main method like so:

Screen Shot 2016-03-01 at 1.05.22 PM

The first way of importing shown above just imports the Scanner Class, whereas the second imports the entire utility library.

Once it is imported, you can create an instance of the class. This is done like so:

Scanner name = new Scanner(System.in);

This name can be anything. For example:

Screen Shot 2016-03-01 at 1.06.04 PM

Methods in the Scanner Class

next() – This grabs the next input which can be any number of characters until it encounters a break.

This looks like:

Screen Shot 2016-03-01 at 1.09.21 PM

nextLine() – This grabs the next whole line until it encounters a new line character, “\n”.

This looks like:

Screen Shot 2016-03-01 at 1.09.43 PM

nextInt() – This grabs the next int

This looks like:

Screen Shot 2016-03-01 at 1.10.23 PM

Note: All other number types follow the same layout as int does. For example nextDouble(), nextFloat(), etc.

If reading from a text file, it is useful to know if there is more input. This can be done by calling hasNext(). hasNext() just like next() can be specified to a certain variable type like so: hasNextInt(), hasNextLine(), etc.

Asking the User for Input

To ask the user for input, a message must be output. There are two ways in which this can be done.

Screen Shot 2016-03-01 at 1.15.49 PM

or

Screen Shot 2016-03-01 at 1.12.09 PM

The first outputs the message in the brackets, then has a built in new line character. The second will output, then stay on the same line until otherwise told. So to output something where the user inputs on the same line as the output, the latter is preferred.

This looks like this:

Screen Shot 2016-03-01 at 1.24.30 PM

Which outputs this to the console:

Screen Shot 2016-03-01 at 1.24.50 PM

 

Please follow and like us:

Leave a Comment


This site uses Akismet to reduce spam. Learn how your comment data is processed.

Facebook
Facebook
Google+
Google+
http://aiclarke.com/2016/03/01/reading-user-input-using-the-scanner-class-in-java">
YouTube
LinkedIn
RSS