The challenge here is to read lines of input until you reach EOF, then number and print all lines of content.

 Hint: Java's Scanner.hasNext() method is helpful for this problem.

Input Format

Read some unknown  lines of input from stdin(System.in) until you reach EOF; each line of input contains a non-empty String.

Output Format

For each line, print the line number, followed by a single space, and then the line content received as input.

Sample Input

Hello world
I am a file
Read me until end-of-file.

Sample Output

1 Hello world
2 I am a file
3 Read me until end-of-file.
Solution:
import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
          Scanner scanner = new Scanner(System.in);
       
        int lineNumber = 1;
       
        // Read input until EOF
        while (scanner.hasNext()) {
            String line = scanner.nextLine();  // Read the next line of input
            System.out.println(lineNumber + " " + line);  // Print the line number followed by the line content
            lineNumber++;  // Increment the line number
        }
       
        scanner.close();
    }
}

Popular posts from this blog

When a method in a subclass overrides a method in superclass, it is still possible to call the overridden method using super keyword - Hacker Rank Solution.

You are given a date. You just need to write the method getDay which returns the day on that date - Hacker Rank Solution.

Java's System.out.printf function can be used to print formatted output. The purpose of this exercise is to test your understanding of formatting output using printf. To get you started, a portion of the solution is provided for you in the editor; you must format and print the input to complete the solution.