杰瑞科技汇

Java hasnextLine()如何判断行尾?

Of course! Let's dive deep into hasNextLine() in Java. This is a fundamental method when working with input, especially from files or the console.

Java hasnextLine()如何判断行尾?-图1
(图片来源网络,侵删)

What is hasNextLine()?

hasNextLine() is a method of the java.util.Scanner class. Its purpose is simple but crucial:

It checks if there is another line of input available to be read.

It does not read the line. It just looks ahead and returns true if the scanner's input source has at least one more line, and false otherwise.

Think of it like looking at the end of a line of text. hasNextLine() asks, "Is there more text on the next line?" It doesn't move your cursor; it just checks.

Java hasnextLine()如何判断行尾?-图2
(图片来源网络,侵删)

The Key Difference: hasNextLine() vs. nextLine()

This is the most common point of confusion for beginners. Let's clarify with a table and an example.

Method Action Returns What it does
hasNextLine() Checks for a line boolean (true or false) Returns true if the input has another line, false if it's at the end. The scanner's position is not advanced.
nextLine() Reads a line String Reads the current line of input (including leading whitespace) and moves the scanner's position to the beginning of the next line.

Simple Example: Reading from the Console

This is the most common use case. You want to keep asking the user for input until they decide to stop.

import java.util.Scanner;
public class HasNextLineExample {
    public static void main(String[] args) {
        // Create a Scanner object to read from the console (System.in)
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter your text (press Enter on an empty line to finish):");
        // Loop as long as there is another line available to read
        while (scanner.hasNextLine()) {
            // Read the line of text
            String line = scanner.nextLine();
            // Check if the user entered an empty line to signal the end
            if (line.isEmpty()) {
                System.out.println("Empty line detected. Exiting.");
                break; // Exit the loop
            }
            // Process the line (in this case, just print it back)
            System.out.println("You entered: " + line);
        }
        // It's very important to close the scanner to free up system resources
        scanner.close();
    }
}

How it Works:

  1. Scanner scanner = new Scanner(System.in); creates a scanner tied to your keyboard.
  2. while (scanner.hasNextLine()) starts the loop. It checks if the user has typed something and pressed Enter (which creates a new line).
  3. Inside the loop, scanner.nextLine() reads the entire line the user just typed.
  4. if (line.isEmpty()) checks if the user simply pressed Enter without typing anything. If so, it prints a message and break; exits the loop.
  5. If the line wasn't empty, it prints what was entered.
  6. The loop repeats, asking hasNextLine() again. If you type Ctrl+D (on Linux/macOS) or Ctrl+Z then Enter (on Windows), hasNextLine() will return false, and the loop will terminate gracefully.
  7. scanner.close() is essential to prevent resource leaks.

Advanced Example: Reading from a File

hasNextLine() is extremely useful for processing files line by line without loading the entire file into memory.

Let's say you have a file named data.txt with the following content:

Java hasnextLine()如何判断行尾?-图3
(图片来源网络,侵删)
apple
banana
cherry
date

Here's the Java code to read it:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadFileWithScanner {
    public static void main(String[] args) {
        try {
            File myFile = new File("data.txt");
            Scanner fileScanner = new Scanner(myFile);
            System.out.println("Reading file contents:");
            // Loop while there are more lines in the file
            while (fileScanner.hasNextLine()) {
                // Read the current line
                String fruit = fileScanner.nextLine();
                System.out.println("Found fruit: " + fruit);
            }
            // Close the scanner
            fileScanner.close();
        } catch (FileNotFoundException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }
}

Output:

Reading file contents:
Found fruit: apple
Found fruit: banana
Found fruit: cherry
Found fruit: date

Important Considerations and Pitfalls

NoSuchElementException

If you call nextLine() when hasNextLine() would return false, your program will crash with a NoSuchElementException.

Bad Code:

Scanner scanner = new Scanner(""); // Scanner with no input
// This will throw an exception because there is no next line
String line = scanner.nextLine(); 

Good Practice (The hasNextLine() Guard): Always use hasNextLine() to check before calling nextLine().

Scanner scanner = new Scanner("");
if (scanner.hasNextLine()) {
    String line = scanner.nextLine();
    System.out.println(line);
} else {
    System.out.println("No input available.");
}

The Scanner Lifecycle

A Scanner has an internal buffer. When it reaches the end of its input source (like the end of a file or the end of console input), it's "closed" in the sense that it has no more data. Calling hasNextLine() again will continue to return false.

Performance

For most applications, hasNextLine() is very fast. It's a simple check on the underlying input stream. You don't need to worry about performance unless you are reading millions of lines in a tight loop, in which case the overhead of the Scanner class itself might become a concern (and you might consider a BufferedReader).

Summary

Feature Description
Class java.util.Scanner
Purpose To check if the input source has another line of text.
Return Type boolean (true if a line exists, false otherwise).
Side Effect None. It does not advance the scanner's position.
Common Use Case Pre-loop condition to read all lines from a file or console input until the end.
Safety Prevents NoSuchElementException by acting as a guard for nextLine().
分享:
扫描分享到社交APP
上一篇
下一篇