Java Scanner nextInt() Method

The nextInt() method in Java, part of the java.util.Scanner class, is used to retrieve the next token from the input as an int value. This method is useful for reading and processing integer values from the input.

Table of Contents

  1. Introduction
  2. nextInt() Method Syntax
  3. Understanding nextInt()
  4. Examples
    • Basic Usage
    • Using a Custom Radix
    • Handling Input Errors
  5. Real-World Use Case
  6. Conclusion

Introduction

The nextInt() method returns the next token from the scanner's input as an int. This method is useful when you need to read and process integer values.

nextInt() Method Syntax

There are two versions of the nextInt() method:

Default Radix

public int nextInt()

Custom Radix

public int nextInt(int radix)

Parameters:

  • radix: The radix (base) to be used for interpreting the token as an int.

Returns:

  • The next token as an int value.

Throws:

  • InputMismatchException: If the next token does not match the int regular expression, or is out of range.
  • NoSuchElementException: If no more tokens are available.
  • IllegalStateException: If the scanner is closed.

Understanding nextInt()

The nextInt() method retrieves the next token and converts it to an int. If the token cannot be interpreted as an int, an InputMismatchException is thrown.

Examples

Basic Usage

To demonstrate the basic usage of nextInt(), we will create a Scanner object and use it to read int values from a string.

Example

import java.util.Scanner;

public class NextIntExample {
    public static void main(String[] args) {
        String input = "10 20 30";

        // Create Scanner object in try-with-resources to ensure it closes automatically
        try (Scanner scanner = new Scanner(input)) {

            while (scanner.hasNextInt()) {
                int value = scanner.nextInt();
                System.out.println("Int value: " + value);
            }
        } // Scanner is automatically closed here
    }
}

Output:

Int value: 10
Int value: 20
Int value: 30

Using a Custom Radix

This example shows how to use nextInt(int radix) to read int values with a specific radix.

Example

import java.util.Scanner;

public class NextIntWithRadixExample {
    public static void main(String[] args) {
        String input = "1010 1111";

        // Create Scanner object in try-with-resources to ensure it closes automatically
        try (Scanner scanner = new Scanner(input)) {

            while (scanner.hasNextInt(2)) { // Check for binary numbers (base 2)
                int value = scanner.nextInt(2);
                System.out.println("Int value (binary): " + value);
            }
        } // Scanner is automatically closed here
    }
}

Output:

Int value (binary): 10
Int value (binary): 15

Handling Input Errors

This example shows how to handle errors when the input token cannot be interpreted as an int.

Example

import java.util.InputMismatchException;
import java.util.Scanner;

public class HandleInputErrorsExample {
    public static void main(String[] args) {
        String input = "10 abc 20";

        // Create Scanner object in try-with-resources to ensure it closes automatically
        try (Scanner scanner = new Scanner(input)) {

            while (scanner.hasNext()) {
                try {
                    int value = scanner.nextInt();
                    System.out.println("Int value: " + value);
                } catch (InputMismatchException e) {
                    System.out.println("Invalid input: " + scanner.next());
                }
            }
        } // Scanner is automatically closed here
    }
}

Output:

Int value: 10
Invalid input: abc
Int value: 20

Real-World Use Case

Reading Configuration Data

In real-world applications, the nextInt() method can be used to read and process integer configuration data from a file.

Example

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ConfigParser {
    public static void main(String[] args) {
        try (Scanner scanner = new Scanner(new File("config.txt"))) {
            while (scanner.hasNext()) {
                try {
                    int value = scanner.nextInt();
                    System.out.println("Configuration value: " + value);
                } catch (InputMismatchException e) {
                    System.out.println("Invalid input: " + scanner.next());
                }
            }
        } catch (FileNotFoundException e) {
            System.out.println("File not found: " + e.getMessage());
        } // Scanner is automatically closed here
    }
}

Output (Assuming config.txt contains valid and invalid int values):

Configuration value: 10
Invalid input: abc
Configuration value: 20
...

Conclusion

The Scanner.nextInt() method is used to retrieve the next token from the input as an int value. This method is particularly useful for applications requiring integer input values. By understanding and using this method, you can efficiently parse and handle int input data. Always close the Scanner using try-with-resources to ensure proper resource management.

Comments