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.
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:
Hello world I am a file Read me until end-of-file.
1 Hello world 2 I am a file 3 Read me until end-of-file.
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).
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(); } }
Import Required Packages: We import java.util.Scanner to use the Scanner class for reading input.
Initialize Scanner: We create a Scanner object to read from standard input (System.in).
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().
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.
Close Scanner: Although not strictly necessary here, it's a good practice to close the Scanner when you're done to avoid resource leaks.
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.
The above is the detailed content of Read Input Until EOF (End-of-File) and Number Your Lines Effortlessly | Competitive Programming Java. For more information, please follow other related articles on the PHP Chinese website!