Accepting user input using Scanner Class In Java

Introducing “System.in”

Before we can understand the use of the Scanner class in java, we first need to understand how java interacts by default with the keyboard. In java, just as we have an object reference called “System.out” that is used to write to the
console window, we also have another object called “System.in” to read keyboard input. So we can say that “System.in” represents InputStream i.e. java keyboard.

The object reference System.in has a method called read( ), which can read keyboard input.

The declaration of read ( ) is as below:

public int read( )

Scanner Class In Java

But it has two problems

It can only accept single character/digit/symbol

It converts every input value it has read to character

Output:

Output:

From the previous examples we can conclude that using read( ) method is useful only when we want to accept a single character as input .

For all other inputs we have to use Scanner class

Scanner Class

Scanner class belongs to the package java.util i.e. utility. To use this class we have to import it by writing

import java.util.Scanner;

It has various methods using which we can accept inputs of all primitive data type, except character type.

Scanner class can be used to scan data not only from keyboard but also from various other input resources like files, network socket, web servers etc

To use Scanner class we will first have to connect it with an input device like keyboard .

This is done using the following statement:

Scanner kb=new Scanner(System.in);

Scanner Class In Java

Important Methods of Scanner class to accept input of primitive data types
int nextInt( )
short nextShort( )
long nextLong( )
float nextFloat( )
byte nextByte( )
double nextDouble( )
boolean nextBoolean( )
For strings
String next( )
String nextLine( )

Accepting Integer

Output

Accepting String

The next( ) method can accept string inputs without any spaces in between i.e. it can only accept single word as input

Whereas, the nextLine( ) method can accept strings with spaces in between i.e. it can accept a complete line of input

Output:

InputMismatchException

When Scanner is given wrong input it gives an exception. i.e. when the data type and method called does not match.

The exception is named as InputMismatchException.

Sample output :-

Checkout the below program to add 2 no.s given by user in java
Program two add 2 no.s given by user

Scanner Class In Java

Shubham Tripathi

Java Developer (Full Stack) , Passionate about creating impact on scale | striving for a continuous improvement | learning entire gamut of Computer technologies | Raising my technical skills & trying to become a better person everyday |

    See all posts by admin