Java End-of-file HackerRank Problem – Coder In Me

Here the challenge of Java End-of-file HackerRank Problem is to read n lines of input until you reach EOF, then number and print all lines of content.

EOF represents  — end-of-file.

To solve  Java End-of-file HackerRank Problem  we take a hint like this-

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

HERE–   hasNext() checks if there is a string remaining in the Scanner; and returns false only when nothing is left there, which is equivalent to EOF.

Input Format for Java End-of-file HackerRank Problem –

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

System.in is an InputStream which is typically connected to keyboard input of console programs.

 

Output Format

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

Input Example

 

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

 

Output Example

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

How To Solve Java End-of-file HackerRank Problem –

  •  for count the line number use line_num as integer type.
  • for EOF use hasNext() method.
  • system.in is used for input operation.

THE CODE :

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 sc = new Scanner(System.in);
        int line_num = 0;
        while(sc.hasNext())
        	System.out.println(++line_num + " " + sc.nextLine());
        sc.close();
    }
}

For more HackerRank problem solution click here

All rights reserved. No part of this Post may be copied, distributed, or transmitted in any form or by any means, without the prior written permission of the website admin, except in the case of brief quotations embodied in critical reviews and certain other noncommercial uses permitted by copyright law. For permission requests, write to the owner, addressed “Attention: Permissions Coordinator,” to the admin @coderinme

 

Leave a reply:

Your email address will not be published.