DEV Community

Cover image for Read Input Until EOF (End-of-File) and Number Your Lines Effortlessly | Competitive Programming Java
Mohammad Ezzeddin Pratama
Mohammad Ezzeddin Pratama

Posted on

Read Input Until EOF (End-of-File) and Number Your Lines Effortlessly | Competitive Programming Java

How to Read Input Until End of File (EOF) in Java

When dealing with input in Java, there might be situations where you don't know the number of lines you're going to read in advance. This is common in coding challenges or scenarios where you're reading from a file or stream until the end. In this post, I’ll show you a simple way to handle this using Java.

Problem Overview

Imagine you're given an unknown number of lines as input. Your task is to read all the lines until the end-of-file (EOF) and print each line, prefixed with its line number.

Here's what the input/output looks like:

Input:

Hello world
I am a file
Read me until end-of-file.
Enter fullscreen mode Exit fullscreen mode

Output:

1 Hello world
2 I am a file
3 Read me until end-of-file.
Enter fullscreen mode Exit fullscreen mode

The Java Approach

Java provides a handy way to handle such problems with the Scanner class and its hasNext() method. This method allows us to read input until there's no more data to read (EOF).

Code Solution

Let’s dive straight into the code:

import java.io.*;
import java.util.*;

public class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        for (int i = 1; sc.hasNext(); i++) {      
            String line = sc.nextLine();
            System.out.println(i + " " + line);
        }

        sc.close();
    }
}
Enter fullscreen mode Exit fullscreen mode

Explanation

  1. Import Required Packages: We import java.util.Scanner to use the Scanner class for reading input.

  2. Initialize Scanner: We create a Scanner object to read from standard input (System.in).

  3. Read Until EOF: The for loop is designed to read lines until there's no more input. The condition sc.hasNext() checks if there's more input to read. If there is, it reads the next line with sc.nextLine().

  4. Print with Line Number: For every line read, we print it along with its line number. We use a loop counter i that starts from 1 and increments with each iteration.

  5. Close Scanner: Although not strictly necessary here, it's a good practice to close the Scanner when you're done to avoid resource leaks.

Key Takeaways

  • The Scanner class in Java, with its hasNext() method, is a great tool for reading input until EOF.
  • Use sc.nextLine() to read each line of input.
  • Keep track of the line number using a simple counter.

Final Thoughts

This approach is simple yet effective for reading an unknown number of lines until EOF in Java. It comes in handy during competitive programming, file reading tasks, or any situation where you're dealing with streams of data.

Happy coding! 🚀

Top comments (0)