Site icon TestingDocs.com

How to get input from keyboard using Scanner class

Introduction

In this tutorial, we will write a simple java program to get input from the keyboard using the Scanner class.

Import Scanner

We can import the Scanner class in the Java program using the below import statement. Alternatively, hover the mouse on the class name, Right-click, and select the import statement.

import java.util.Scanner;

 

Scanner class

A Scanner breaks the input entered by the user into tokens using a
delimiter pattern, which by default matches whitespace. The resulting
tokens are then converted into different data types using the methods of the class.

Scanner keyboard = new Scanner(System.in);

System.in is the standard InputStream. The stream is open and ready to supply keyboard input data. Typically this depends on the source specified by
the host environment or user.

Code Snippet

import java.util.Scanner;

public class KeyboardInputDemo {

  public static void main(String[] args)
  {	Scanner keyboard = new Scanner(System.in);
    System.out.print( "Please enter your name :="  );
    String name = keyboard.nextLine();
    System.out.println( "Output = Hello " + name + " !" );
    keyboard.close();
  }
}

 

Sample Output

Please enter your name :=TestingDocs
Output = Hello TestingDocs !

 

 

Common mistake

Importing a different Scanner class and trying to run the program without resolving the compilation errors would result in Program error:

Exception in thread “main” java.lang.Error: Unresolved compilation problems:
Scanner cannot be resolved to a type

Exit mobile version