Java end of file

eofjavastring

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner line = new Scanner(System.in);
        int counter = 1;
        
        while (line.hasNextLine()) {
            String line = line.nextLine();

            System.out.println(counter + " " + line);
            counter++;
        }
    }
}

Task: Each line will contain a non-empty string. Read until EOF.
For each line, print the line number followed by a single space and the line content.

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.

Best Solution

If you'd like to scan from a file, you can use the below code.

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Solution {

    public static void main(String[] args) throws FileNotFoundException {
        Scanner scan = new Scanner(new File("input.txt"));
        int counter = 1;
        while (scan.hasNextLine()) {
            String line = scan.nextLine();
            System.out.println(counter + " " + line);
            counter++;
        }
    }
}