Java provides various ways to read input from the keyboard.
Scanner class is one of them.
Scanner class in Java is found in the java.util package.
It is the simplest way to get input in Java.
By the help of Scanner in Java, we can get input from the user in primitive types such as int, long, double, byte, float, short, etc.
The Java Scanner class provides nextXXX( ) methods to return the type of value such as :-
nextInt( ), nextByte( ), nextShort( ), next( ), nextLine( ), nextDouble( ), nextFloat( ), nextBoolean( ), etc.
To get a single character from the scanner, you can call next().charAt(0) method which returns a single character.
To get the instance of Java Scanner which reads input from the user, we need to pass the input stream (System.in) in the constructor of Scanner class.
For Example:
Scanner in = new Scanner(System.in);
int i ;
i= in.nextInt();
Java program using Scanner
import java.util.*;
public class ScannerClassExample {
public static void main(String args[]){
Scanner in = new Scanner (System.in);
System.out.println("--------Enter Your Details-------- ");
System.out.print("Enter your name: ");
String name = in.next();
System.out.println("Name: " + name);
System.out.print("Enter your age: ");
int i = in.nextInt();
System.out.println("Age: " + i);
System.out.print("Enter your salary: ");
double d = in.nextDouble();
System.out.println("Salary: " + d);
in.close();
}
}
Output : -
------Enter Your Details--------
Enter your name: Abhishek
Name: Abhishek
Enter your age: 23
Age: 23
Enter your salary: 25000
Salary: 25000.0
On this page of the site you can watch the video online Java - 6 | How to take input in Java | input in java using Scanner with a duration of hours minute second in good quality, which was uploaded by the user Rishi Yadav 07 August 2020, share the link with friends and acquaintances, this video has already been watched 77 times on youtube and it was liked by 7 viewers. Enjoy your viewing!