Java End-of-file Solution


Problem Overview

Original Problem: Java End-of-file | Hackerrank

Difficulty: Easy

Category: Input / Output

Description: We are given an unknown number of input lines. Our task is to read each line from standard input until we reach the end of the input stream (EOF). For each line read, we must output the line number (starting from 1), followed by the line content.

Understanding the Problem

This is a simple problem with no complex data structures or algorithms involved. The main challenge lies in determining when to stop reading input, which is when we reach the end of file (EOF).

To solve this, we’ll need a way to:

  • Continuously read input line by line.

  • Detect the end of the input stream.

  • Print each line along with its corresponding line number.

Input:

An unknown number of lines of text

Output:

For every line of input, the number of the line is printed (starting from one) and the line content

Initial Reasoning

The original problem doesn’t provide any starter code, so we’ll need to decide:

  • How to read input from System.in.

  • How to detect the end of the input.

Java’s Scanner class is ideal for this task. We can use its hasNextLine() method to keep reading until there are no more lines. A simple counter will help track the line numbers.

Pseudocode

// Main function:
Initialize a Scanner object to read from standard input.
Initialize a line counter to 1.
While there is another line to read:
    Read the next line.
    Print the line counter and the line content.
    Increment the line counter.

Solution Code

// Note this is one of many possible solutions
import java.util.Scanner;

public class Solution {
    public static void main(String[] args) {
        // Create a Scanner object to read from System.in
        Scanner scanner = new Scanner(System.in);

        // Initialize line number counter starting at 1
        int lineNumber = 1;

        // Keep reading lines while there is another line of input
        while (scanner.hasNextLine()) {
            // Read the next line
            String line = scanner.nextLine();

            // Print the line number and the line content
            System.out.println(lineNumber + " " + line);

            // Increment the counter for the next line
            lineNumber++;
        }

        // Close the scanner 
        scanner.close();
    }
}