Java Scanner next() Method

The next() method in Java, part of the java.util.Scanner class, is used to retrieve the next complete token from the input. This method advances the scanner past the current token.

Table of Contents

  1. Introduction
  2. next() Method Syntax
  3. Understanding next()
  4. Examples
    • Basic Usage
    • Using a Custom Delimiter
  5. Real-World Use Case
  6. Conclusion

Introduction

The next() method returns the next complete token from the scanner's input. It is typically used to process input tokens one at a time, and it advances the scanner to the next token.

next() Method Syntax

The syntax for the next() method is as follows:

public String next()

Parameters:

  • This method does not take any parameters.

Returns:

  • The next complete token as a String.

Throws:

  • NoSuchElementException: If no more tokens are available.
  • IllegalStateException: If the scanner is closed.

Understanding next()

The next() method retrieves and returns the next complete token from the input. Tokens are usually separated by whitespace, but you can change the delimiter using the useDelimiter() method.

Examples

Basic Usage

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

Example

import java.util.Scanner;

public class NextExample {
    public static void main(String[] args) {
        String input = "Hello world!";

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

            while (scanner.hasNext()) {
                System.out.println("Token: " + scanner.next());
            }
        } // Scanner is automatically closed here
    }
}

Output:

Token: Hello
Token: world!

Using a Custom Delimiter

This example shows how to use a custom delimiter to split the input into tokens.

Example

import java.util.Scanner;

public class CustomDelimiterExample {
    public static void main(String[] args) {
        String input = "apple,banana,cherry";

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

            while (scanner.hasNext()) {
                System.out.println("Token: " + scanner.next());
            }
        } // Scanner is automatically closed here
    }
}

Output:

Token: apple
Token: banana
Token: cherry

Real-World Use Case

Parsing CSV Data

In real-world applications, the next() method can be used to parse CSV data, where each token represents a cell value in the CSV.

Example

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

public class CSVParser {
    public static void main(String[] args) {
        try (Scanner scanner = new Scanner(new File("data.csv"))) {
            scanner.useDelimiter(",");

            while (scanner.hasNext()) {
                System.out.println("Cell value: " + scanner.next());
            }
        } catch (FileNotFoundException e) {
            System.out.println("File not found: " + e.getMessage());
        } // Scanner is automatically closed here
    }
}

Output (Assuming data.csv contains comma-separated values):

Cell value: value1
Cell value: value2
Cell value: value3
...

Conclusion

The Scanner.next() method is used to retrieve the next complete token from the input. It is commonly used to process tokens from a string, file, or other input sources. By understanding and using this method, you can efficiently parse and handle different types of input data. Always close the Scanner using try-with-resources to ensure proper resource management.

Comments