Java Scanner hasNextLine() Method

The hasNextLine() method in Java, part of the java.util.Scanner class, is used to check if there is another line in the input. This method is useful for processing multi-line input.

Table of Contents

  1. Introduction
  2. hasNextLine() Method Syntax
  3. Understanding hasNextLine()
  4. Examples
    • Basic Usage
    • Reading Lines from a File
  5. Real-World Use Case
  6. Conclusion

Introduction

The hasNextLine() method returns true if there is another line of input, and false otherwise. It is typically used to process input line by line.

hasNextLine() Method Syntax

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

public boolean hasNextLine()

Parameters:

  • This method does not take any parameters.

Returns:

  • true if there is another line of input; false otherwise.

Throws:

  • IllegalStateException: If the scanner is closed.

Understanding hasNextLine()

The hasNextLine() method checks if there is another line available in the input. It does not advance the scanner past the current line but allows you to safely call nextLine() to retrieve the next line.

Examples

Basic Usage

To demonstrate the basic usage of hasNextLine(), we will create a Scanner object and read input line by line.

Example

import java.util.Scanner;

public class HasNextLineExample {
    public static void main(String[] args) {
        String input = "Line 1\nLine 2\nLine 3";

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

            // Check and print lines while there are more lines
            while (scanner.hasNextLine()) {
                System.out.println("Line: " + scanner.nextLine());
            }
        } // Scanner is automatically closed here
    }
}

Output:

Line: Line 1
Line: Line 2
Line: Line 3

Reading Lines from a File

This example shows how to use hasNextLine() to read lines from a file.

Example

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

public class ReadLinesFromFile {
    public static void main(String[] args) {
        try (Scanner scanner = new Scanner(new File("example.txt"))) {

            // Check and print lines while there are more lines
            while (scanner.hasNextLine()) {
                System.out.println("Line: " + scanner.nextLine());
            }
        } catch (FileNotFoundException e) {
            System.out.println("File not found: " + e.getMessage());
        } // Scanner is automatically closed here
    }
}

Output (Assuming example.txt contains multiple lines):

Line: First line of text
Line: Second line of text
Line: Third line of text

Real-World Use Case

Processing Multi-Line User Input

In real-world applications, hasNextLine() can be used to process multi-line user input or read multi-line data from various sources, such as files, network streams, or standard input.

Example

import java.util.Scanner;

public class MultiLineInputProcessor {
    public static void main(String[] args) {
        System.out.println("Enter multiple lines of text (type 'exit' to quit):");

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

            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                if (line.equalsIgnoreCase("exit")) {
                    break;
                }
                System.out.println("You entered: " + line);
            }
        } // Scanner is automatically closed here
    }
}

Conclusion

The Scanner.hasNextLine() method is useful for checking if there is another line in the input. It is commonly used to process multi-line input from various sources. Always close the Scanner using try-with-resources to ensure proper resource management.

Comments