Java Scanner hasNext()

In this guide, you will learn about the Scanner hasNext() method in Java programming and how to use it with an example.

1. Scanner hasNext() Method Overview

Definition:

The hasNext() method of the Scanner class in Java checks if there is another token available in the input of this scanner. This method is particularly useful in loops to check if there's more data to process.

Syntax:

public boolean hasNext()

Parameters:

This method does not take any parameters.

Key Points:

- The method returns true if there's another token available, otherwise, it returns false.

- This method is blocking, which means if you call it, it might wait indefinitely until there's more input (like if the input source is the console).

- It does not advance the scanner past any input.

2. Scanner hasNext() Method Example

import java.util.Scanner;

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

        System.out.println("Enter some words, type 'exit' to quit:");
        while(scanner.hasNext()) {
            String word = scanner.next();
            if("exit".equalsIgnoreCase(word)) {
                break;
            }
            System.out.println("You entered: " + word);
        }
    }
}

Output:

Enter some words, type 'exit' to quit:
hello
You entered: hello
world
You entered: world
exit

Explanation:

In this example, the program prompts the user to enter words. It uses the hasNext() method to determine if there is another word available in the input. The loop keeps reading words until the user enters 'exit', which will break out of the loop.

Comments