Java Scanner hasNext() Method

The hasNext() method in Java, part of the java.util.Scanner class, is used to check if the Scanner has another token in its input. There are several overloaded versions of this method, which allow you to check for the presence of the next token based on different conditions.

Table of Contents

  1. Introduction
  2. hasNext() Method Syntax
  3. Understanding hasNext()
  4. Examples
    • Basic Usage
    • Checking for Specific Patterns
    • Checking for Specific Types
  5. Real-World Use Case
  6. Conclusion

Introduction

The hasNext() method determines whether the Scanner has another token in its input. The overloaded versions of this method allow for more specific checks, such as checking for a specific pattern or data type.

hasNext() Method Syntax

There are several overloaded versions of the hasNext() method:

Basic Version

public boolean hasNext()

Using a String Pattern

public boolean hasNext(String pattern)

Using a Pattern Object

public boolean hasNext(Pattern pattern)

Checking for a Specific Type

public boolean hasNextInt()
public boolean hasNextInt(int radix)
public boolean hasNextDouble()
public boolean hasNextFloat()
public boolean hasNextLong()
public boolean hasNextLong(int radix)
public boolean hasNextBoolean()
public boolean hasNextShort()
public boolean hasNextShort(int radix)
public boolean hasNextByte()
public boolean hasNextByte(int radix)

Parameters:

  • pattern: A String or Pattern representing the regular expression to be matched.
  • radix: The radix (base) to be used for interpreting the token as an integer or long.

Returns:

  • true if the scanner has another token that matches the criteria; false otherwise.

Throws:

  • IllegalStateException: If the scanner is closed.

Understanding hasNext()

The hasNext() method checks if there is another token available in the scanner's input. The basic version checks for any token, while the overloaded versions check for specific patterns or data types.

Examples

Basic Usage

To demonstrate the basic usage of hasNext(), we will create a Scanner object and check if it has more tokens.

Example

import java.util.Scanner;

public class HasNextExample {
    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)) {

            // Check and print tokens while there are more tokens
            while (scanner.hasNext()) {
                System.out.println("Token: " + scanner.next());
            }
        } // Scanner is automatically closed here
    }
}

Output:

Token: hello
Token: world

Checking for Specific Patterns

This example shows how to use hasNext(String pattern) to check for specific patterns in the input.

Example

import java.util.Scanner;

public class HasNextPatternExample {
    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)) {

            // Check and print six-letter words
            while (scanner.hasNext("\\b[a-z]{6}\\b")) {
                System.out.println("Found a six-letter word: " + scanner.next());
            }
        } // Scanner is automatically closed here
    }
}

Checking for Specific Types

This example shows how to use hasNextInt() and hasNextDouble() to check for specific data types in the input.

Example

import java.util.Scanner;

public class HasNextTypeExample {
    public static void main(String[] args) {
        String input = "123 45.67 true";

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

            // Check and print integer token
            if (scanner.hasNextInt()) {
                System.out.println("Next token is an integer: " + scanner.nextInt());
            }

            // Check and print double token
            if (scanner.hasNextDouble()) {
                System.out.println("Next token is a double: " + scanner.nextDouble());
            }

            // Check and print boolean token
            if (scanner.hasNextBoolean()) {
                System.out.println("Next token is a boolean: " + scanner.nextBoolean());
            }
        } // Scanner is automatically closed here
    }
}

Output:

Next token is an integer: 123
Next token is a double: 45.67
Next token is a boolean: true

Real-World Use Case

Parsing Mixed Data Types

In real-world applications, the hasNext() method can be used to parse input that contains mixed data types, ensuring that each token is processed correctly.

Example

import java.util.Scanner;

public class MixedDataTypesParser {
    public static void main(String[] args) {
        String input = "42 3.14 false 101";

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

            // Check and print tokens of various types
            while (scanner.hasNext()) {
                if (scanner.hasNextInt()) {
                    System.out.println("Found an integer: " + scanner.nextInt());
                } else if (scanner.hasNextDouble()) {
                    System.out.println("Found a double: " + scanner.nextDouble());
                } else if (scanner.hasNextBoolean()) {
                    System.out.println("Found a boolean: " + scanner.nextBoolean());
                } else {
                    System.out.println("Found a string: " + scanner.next());
                }
            }
        } // Scanner is automatically closed here
    }
}

Output:

Found an integer: 42
Found a double: 3.14
Found a boolean: false
Found an integer: 101

Conclusion

The Scanner.hasNext() method and its overloaded versions provide a way to check for the presence of the next token in the input, based on various conditions such as patterns or data types. By understanding and using these methods, you can efficiently parse and process different types of input data. Whether you are working with simple tokens or mixed data types, the hasNext() method offers a reliable way to handle token presence checks in your Java applications. Always remember to close the Scanner using try-with-resources to ensure proper resource management.

Comments