A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/java/scanner-class-in-java/ below:

Scanner Class in Java - GeeksforGeeks

Scanner Class in Java

Last Updated : 23 Jul, 2025

In Java, the Scanner class is present in the java.util package is used to obtain input for primitive types like int, double, etc., and strings. We can use this class to read input from a user or a file. In this article, we cover how to take different input values from the user using the Scanner class.

Example 1: Taking input from the user using the Scanner class and displaying the output.

Java
// Java program to demonstrate the use of Scanner class
// to take input from user
import java.util.Scanner;

class Geeks 
{
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        System.out.println("Enter your name:");
        String name = sc.nextLine();

        System.out.println("Hello, " + name + " Welcome to the GeeksforGeeks.");

    }

}

Output:

Explanation: In the above code example, we use the nextLine() of Scanner class to read the line value which is entered by the user and print it in the console.

Steps To Use Scanner Class to Take Input

Step 1: First, import the java.uti.Scanner package in top of the program file Without importing this package, we can not use the Scanner class. either we can import the java.util.* by importing this package we can use all the classes present in the util package.

import java.util.Scanner

public class Geeks{

public static void main(String [] args){

}
}

Step 2: Create the object of the Scanner class.

Scanner sc = new Scanner (System.in);

Here "sc" is an object of the Scanner class. We can give it different names for our ease such as in, var or obj etc. Using this object we can use the methods of the Scanner class.

Step 3: Create a variable and using scanner class object call the corresponding method to take the input value.

int age = sc.nextInt();

Java Scanner Input Types

The scanner class helps take the standard input stream in Java. So, we need some methods to extract data from the stream. The methods used for extracting data are mentioned below:

Let us look at the code snippet to read data of various data types.

Example 2: Taking different inputs using Scanner class method such as nextInt(), nextDouble and nextLine(), etc.

Java
// Java program to read data of various types 
// using Scanner class
import java.util.Scanner;

// Driver Class
public class Geeks
 {
    // main function
    public static void main(String[] args) {
        
        // Declare the object and initialize with
        // predefined standard input object
        Scanner sc = new Scanner(System.in);

        System.out.println("Enter your name:");

        // String input
        String name = sc.nextLine();

        System.out.println("Enter your gender (M/F): ");

        // Character input
        char gender = sc.next().charAt(0);

        // Numerical data input
        // byte, short and float can be read

        System.out.println("Enter your age: ");
        int age = sc.nextInt();

        System.out.println("Enter your cgpa: ");
        double cgpa = sc.nextDouble();

        // Print the values to check if the input was
        // correctly obtained.
        System.out.println("Name: " + name);
        System.out.println("Gender: " + gender);
        System.out.println("Age: " + age);

        System.out.println("CGPA: " + cgpa);
    }
}

Output:

Explanation: In the above code example, we use the Scanner class to take different types of input values from user and print it in the console.

Sometimes, we have to check if the next value we read is of a certain type or if the input has ended (EOF marker encountered). Then, we check if the scanner's input is of the type we want with the help of hasNextDataType() functions where DataType is the type we are interested in. The function returns true if the scanner has a token of that type, otherwise false. For example, in the below code, we have used hasNextInt(). To check for a string, we use hasNextLine(). Similarly, to check for a single character, we use hasNext().charAt(0).

Example 3: Using the hasNext() and hasNextInt() method to take input from user without specifying the limit of input values.

Java
// Java program to read some values using Scanner
// class and print their mean.
import java.util.Scanner;

public class Geeks 
{
    public static void main(String[] args) {
        
        // Declare an object and initialize with
        // predefined standard input object
        Scanner sc = new Scanner(System.in);

        // Initialize sum and count of input elements
        int sum = 0, count = 0;

        System.out.println("Enter integers to calculate the mean (type 'done' to finish):");

        // Loop to read input until "done" is entered
        while (sc.hasNext()) {
            if (sc.hasNextInt()) {
                
                // Read an int value
                int num = sc.nextInt();
                sum += num;
                count++;
            } else {
                String input = sc.next();
                if (input.equalsIgnoreCase("done")) {
                    break;
                } else {
                    System.out.println("Invalid input. Please enter an integer or type 'done' to finish.");
                }
            }
        }

        // Calculate and display the mean
        if (count > 0) {
            // Use double for precise mean calculation
            
            double mean = (double) sum / count; 
            System.out.println("Mean: " + mean);
        } else {
            System.out.println("No integers were input. Mean cannot be calculated.");
        }
     
    }
}

Output:

Explanation: In the above code example, we use the hasNext() and hasNextInt() method to take the input values from user and then user give the input value they can specify that the input value is ended and they can type "done" to find the mean value of given input.

Important Points:



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4