How to read console input in java

276 Flares Twitter 0 Facebook 0 Google+ 276 LinkedIn 0 Filament.io 276 Flares ×

Many java programs requires the ability to take input from the user to proceed further with the program. The programs may present a graphical input element or prompt the user to type in the input in the console. Let us see how can we read the user input from the console in Java.

Java 5, has introduced a class, scanner that simplifies the process for reading input from the console. Scanner is the class you should be familiar with if you want to read the console input entered by the user.

How to read a String from Console using Scanner

Scanner is not just limited to reading string inputs.It can be used to read – int, long, short, float etc as well. Scanner class will throw java.util.InputMismatchException if it encounters an invalid type.

How to read a number from Console using Scanner

The above program tries to read an integer, a number using the Scanner’s nextInt() method in a loop. If it encounters java.util.InputMismatchException the loop continues and terminates when an integer (number) is read.

But is that all to scanner ? No it has more to offer. It can even be asked to scan the input for a pattern, accept the input if it matches and rejects otherwise. Here is a program to show case this feature.

The above program scans the input for a string starting with a single digit number (0-9) and a single capital alphabet. It rejects all other inputs by throwing java.util.InputMismatchException.