Scanner nextInt() Method Example

1. Introduction

The Scanner class in Java is used to parse primitive types and strings using regular expressions. It can parse and read the input from various input sources like strings, files, and streams. The nextInt() method of the Scanner class is used to scan the next token of the input as an int. This method is particularly useful when you need to read numerical input from the console or other input sources. It throws InputMismatchException if the next token does not match the Integer regular expression, or is out of range.

2. Program Steps

1. Import the Scanner class.

2. Create an instance of the Scanner class to read input from System.in.

3. Prompt the user to enter an integer.

4. Use the nextInt() method to read an integer value from the console.

5. Close the Scanner instance.

3. Code Program

import java.util.Scanner;

public class ScannerNextIntExample {
    public static void main(String[] args) {
        // Step 1: Creating a Scanner object to read from the console
        Scanner scanner = new Scanner(System.in);

        // Step 2: Prompting the user for an integer input
        System.out.println("Enter an integer:");

        // Step 3: Reading the integer input
        int number = scanner.nextInt();

        // Step 4: Displaying the entered integer
        System.out.println("You entered: " + number);

        // Step 5: Closing the scanner to avoid resource leak
        scanner.close();
    }
}

Output:

(Example output based on user input "25")
Enter an integer:
You entered: 25

Explanation:

1. The program begins by creating a Scanner object named scanner to read data from the standard input stream (System.in), enabling it to read user input from the console.

2. It then prompts the user to enter an integer by displaying a message on the console.

3. The nextInt() method is called on the scanner object to read the next token from the input as an integer. If the user enters a valid integer, it is read and stored in the variable number.

4. The program prints the integer entered by the user, demonstrating how the nextInt() method can be used to read an integer value from the console.

5. Finally, the Scanner object is closed using the close() method to prevent resource leaks. It's a recommended practice to close the scanner when it's no longer needed.

Comments