I am doing Java exercises from HackerRank.com and bit confused about this problem.
Here is my code that pass the test case.
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// String input = in.nextLine();
int counter = 1;
while (in.hasNext()) {
System.out.println(counter + " " + in.nextLine());
counter++;
}
}
}
We are suppose to print number of lines of input from Scanner, until line of input contains a empty String. The line of inputs are automatically generated by the HackerRank website. For test case, three lines of input will be generated.
Test case input
Hello World
I am a file
Read me until end-of-file.
Expected output
1 Hello World
2 I am a file
3 Read me until end-of-file.
However, whenever I uncomment out the
String input = in.nextLine();
My output only shows first 2 lines instead of all 3. I thought I need that line of code in order to type a line of input. For example,
Scanner sc = new Scanner(System.in);
System.out.println("Enter your name.");
String name = sc.nextLine();
Also when I write
String input = in.next();
instead of nextLine() code, my output shows all 3 lines but first word "Hello" is omitted.
in.next(); output
1 World
2 I am a file
3 Read me until end-of-file.
What I want to know is why I don't need String input = in.nextLine(); to pass the test case.