Java End of File - Hacker Rank Solution
Hello Friends, How are you? Today I am going to solve the HackerRank Java End of File Problem with a very easy explanation. This is the 9th problem of Java on HackerRank. In this article, you will get more than three approaches to solve this problem. So let's start-
HackerRank Java End of File - Problem Statement
"In computing, End Of File (commonly abbreviated EOF) is a condition in a computer operating system where no more data can be read from a data source." — (Wikipedia: End-of-file)
The challenge here is to read n lines of input until you reach EOF, then number and print all n lines of content.
Hint: Java's Scanner.hasNext() method is helpful for this problem.
Input Format
Read some unknown n 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.
Hello world I am a file Read me until end-of-file. (code-box)
1 Hello world 2 I am a file 3 Read me until end-of-file. (code-box)
Java End of File - Hacker Rank Solution
Approach I:
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 scan = new Scanner(System.in); int i = 1; while (scan.hasNextLine()) { System.out.println(i + " " + scan.nextLine()); i++; } scan.close(); } }
import java.io.*; import java.util.*; public class Solution { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int i = 0; while (sc.hasNextLine()) { System.out.println(++i + " " + sc.nextLine()); } } }
import java.io.*; import java.util.*; public class Solution { public static void main(String[] args) { /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ Scanner scanner = new Scanner(System.in); for(int i =1; scanner.hasNext(); i++){ System.out.println(i+" "+scanner.nextLine()); } } }
Disclaimer: The above Problem ( Java End of File ) is generated by Hackerrank but the Solution is Provided by Code Solution. This tutorial is only for Educational and Learning purposes. Authority if any of the queries regarding this post or website fill the contact form.
I hope you have understood the solution to this HackerRank Problem. All the above solutions will pass all the test cases. Now visit the Java End of File HackerRank Problem and try to solve it again.
All the Best!

