DEV Community

Indumathy
Indumathy

Posted on

Scanner Class

Class in Java

Definition
The Scanner class is a predefined class in Java used to take input from the user.
It belongs to:
java.util package

Why Scanner?
It is used to read:
int
double
float
String
boolean
long
etc.

How to Use Scanner

Step 1: Import the package

import java.util.Scanner;

Step 2: Create Scanner Object

Scanner sc = new Scanner(System.in);

✔ System.in → Takes input from keyboard
✔ sc → Object name

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();
String name = sc.nextLine();

The nextLine() may get skipped because nextInt() does not consume the newline.

Correct way:

int age = sc.nextInt();
sc.nextLine(); // consume leftover newline
String name = sc.nextLine();

Common Scanner Methods

nextInt()-Integer
nextDouble() - Decimal number
next() - Single word
nextLine() - Full sentence
nextBoolean() - true/false

Always Close Scanner

sc.close();

Example:
If we want to get the 5 subject marks from user and print the total we can use the scanner class and achieve this.
import java.util. Scanner;
public class TotalMarks {

    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();

        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
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)