Scanner Class in Java
Scanner is a class contained in java.util package basically used for obtaining the input of the primitive types like int, double,and strings. To read input an object of Scanner class is created and various methods are used to read specific input e.g to read string nextLine() is used,to read int nextInt() is used and so on.
Program demonstrating use of Scanner class:
// Java program to read data of various types using Scanner class.
import java.util.Scanner;
public class ScannerDemo
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String name = sc.nextLine(); // String input
char gender = sc.next().charAt(0); // Character input
int age = sc.nextInt(); // Integer input
long mobileNo = sc.nextLong(); // Long input
double cgpa = sc.nextDouble(); // Double input
System.out.println("Name: "+name);
System.out.println("Gender: "+gender);
System.out.println("Age: "+age);
System.out.println("Mobile Number: "+mobileNo);
System.out.println("CGPA: "+cgpa);
}
}
Input :
Suraj
M
20
8976745454
3.44444
Output:
Name: Suraj
Gender: M
Age: 20
Mobile Number: 8976745454
CGPA: 3.44444
0 Comment(s)