Skip to main content

On This Page

Terminating Scanner When Input Is Complete in Java

2 min read
Share

These articles are AI-generated summaries. Please check the original sources for full details.

Terminating Scanner When Input Is Complete in Java

Java’s Scanner class doesn’t automatically stop reading input unless explicitly signaled. Developers must use EOF markers or sentinel values to terminate it gracefully.

Why This Matters

The Scanner class connected to System.in continuously waits for input, assuming more data may follow. This leads to infinite loops unless explicitly terminated, causing resource leaks or unresponsive programs. Improper handling, like checking for null or using ==, fails because hasNextLine() never returns false until an EOF signal is received.

Key Insights

  • “EOF marker required for termination, 2025”: Users must send CTRL+D (Unix) or CTRL+Z (Windows) to signal end-of-input.
  • “Sentinel values over EOF for user clarity”: Using keywords like exit provides explicit control.
  • “Do-while loops ensure at least one input read”: Guarantees processing before termination checks.

Working Example

import java.util.Scanner;
public class EOFExample {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
try {
System.out.println("Enter text (press CTRL+D on Unix/Mac or CTRL+Z on Windows to end):");
while (scan.hasNextLine()) {
String line = scan.nextLine();
System.out.println("You entered: " + line);
}
System.out.println("End of input detected. Program terminated.");
} finally {
scan.close();
}
}
}
import java.util.Scanner;
public class SampleScannerSentinel {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
try {
while (scan.hasNextLine()) {
String line = scan.nextLine().toLowerCase();
if (line.equals("exit")) {
System.out.println("Exiting program...");
break;
}
System.out.println(line);
}
} finally {
scan.close();
}
}
}

Practical Applications

  • Use Case: Command-line tools requiring user input termination.
  • Pitfall: Using == to check for empty strings, leading to incorrect termination logic.

References:


Continue reading

Next article

Terraform Project: Simple EC2 + Security Group

Related Content