Java End-of-file
The challenge here is to read lines of input until you reach EOF, then number and print all lines of content.
Hint: Java's Scanner.hasNext() method is helpful for this problem.
Input Format
Read some unknown 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.
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.SOLUTIONS:import java.io.*;import java.util.*;
public class Solution {
public static void main(String[] args) { Scanner scan = new Scanner(System.in); int i=0; while(scan.hasNextLine()){ String str=scan.nextLine(); if (str.contains("end-of-file")){ i++; System.out.println(i+" "+str); break; }else{ i++; System.out.println(i+" " +str); } } // I don't know why hackerrank didn't accept my below solution. when I run it in eclipse it worked as well as it is required. anyway it is the 2. solution.// Scanner scan = new Scanner(System.in);// int i = 0;// while(true){// String str=scan.nextLine();// if (str.contains("end-of-file")){// i++;// System.out.println(i+" "+str);// break;// }else{// i++;// System.out.println(i+" " +str);
// }
// } }}
Comments
Post a Comment