Scanner Class
Source: Dev.to
Class in Java
Definition of the class concept in Java.
Why Scanner?
The Scanner class simplifies reading input from various sources, such as the keyboard.
How to Use Scanner
Step 1: Import the package
import java.util.Scanner;
Step 2: Create a Scanner object
Scanner sc = new Scanner(System.in);
System.in → Takes input from the keyboard.
Step 3: Take input
int age = sc.nextInt();
String name = sc.nextLine();
double salary = sc.nextDouble();
Important Concept
If you write:
int age = sc.nextInt();
the subsequent nextLine() may be skipped because nextInt() does not consume the newline character.
Correct way
int age = sc.nextInt();
sc.nextLine(); // consume the remaining newline
String name = sc.nextLine();
Common Scanner Methods
nextInt()– reads an integernextLine()– reads a line of textnextDouble()– reads a double
Always Close Scanner
sc.close();
Example
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Tamil mark:");
int tamil = sc.nextInt();
System.out.println("Enter English mark:");
int english = sc.nextInt();
System.out.println("Enter Maths mark:");
int maths = sc.nextInt();
System.out.println("Enter Science mark:");
int science = sc.nextInt();
System.out.println("Enter Social mark:");
int social = sc.nextInt();
sc.nextLine(); // consume newline
System.out.println("Student name:");
String name = sc.nextLine();
int total = tamil + english + maths + science + social;
System.out.println("Total Marks: " + total);
System.out.println("Student name: " + name);
sc.close(); // Good practice
}
}