Slide 1
Slide 2
Slide 3

User input integer in java programming (V24)

No Comments

User Input

To receive input from the user in Java, the Scanner class is used. The Scanner class is a built-in class in the java.util package. The Java Scanner class provides many built-in methods to take different types of input from the user.

How to Use the Scanner Class to Take User Input?

Below are the steps to use the Scanner class for user input in Java:

Step 1: Import the Scanner Class
First, you need to import the Scanner class to use its methods. To import the Scanner class, use the following import statement:


 Step 2: Create a Scanner Class Object

After importing the Scanner class, you need to create an object of it to use its methods. To create an object of the Scanner class, call the Scanner() constructor.

Below is the statement to create an object of the Scanner class:


Step 3: Take User Input
The Scanner class provides many methods that are useful for taking user input of different types. For example, if you want to input an integer value, use the nextInt() method.

Below is the statement to take user input in Java:


The above statement will wait for the user to input an integer. When the user provides an integer value, it will be assigned to the variable age.

Source Code:

Copied!
import java.util.Scanner;

public class IntegerInput {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter an integer: ");
        
        // Check if the input is an integer
        if (scanner.hasNextInt()) {
            int number = scanner.nextInt(); // Read integer input
            System.out.println("You entered: " + number);
        } else {
            System.out.println("Invalid input! Please enter a valid integer.");
        }

        scanner.close();
    }
}

Result:

Watch the video:

Ebook: https://softkhpc.blogspot.com/2025/05/java-programming-ebooks.html

back to top