Introduction
In Java, we have many ways to get input from a user. One of the ways is the Scanner class. It is a very useful class in Java. The Scanner class takes input from the user and prints it as the output.
Scanner class
The Scanner class takes input from the user. The input is broken down into tokens by the Scanner class. White space is used as the delimiter by the Scanner class. It is the default delimiter.
Example
package demo;
import java.util.*;
public class Demo
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
/**creation of object of scanner class **/
String Dept;
System.out.print("Plz tell me your dept---");
Dept = input.next();
/** next method is used**/
String Designation;
System.out.print("Plz tell me your designation---");
Designation = input.next();
/** next method is used**/
String Introduction;
Introduction = "OK you are in " + Dept + " as a " + Designation;
System.out.println(Introduction);
}
}
-
The java.util library contains the Scanner class.
-
Scanner input = new Scanner(System.in); creates the object of the Scanner class. Here new is used to create new objects of a class.
-
System.in is used to inform Java that it is the system input.
-
Here we use the next method. The next method is used to fetch the input from user. It will fetch the next string that is typed by the user by the keyboard.
Output of the program
This is the output when we run the program.
When we run our program it will ask us for our first input and when we give it then it will give us the following output.
After pressing Enter it will again ask for the input and store the previous input into the variable Dept.
When we give the second input it will give the following output.
Now when we press Enter again it will show us the complete output and again store the second input into the second variable Designation.
Summary
This article explains a way to get input from the user with the help of the Scanner class.