Harshit Juneja Harshit Juneja - 1 month ago 6
Java Question

How to use hasNext() from the Scanner class?

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:

Sample Output

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


Here is my solution. The problem being I am not able to proceed till EOF.
But the output is just:

Hello world


Here is my code:

public class Solution {

public static void main(String[] args) {
check(1); // call check method
}

static void check(int count) {
Scanner s = new Scanner(System.in);
if(s.hasNext() == true) {
String ns = s.nextLine();
System.out.println(count + " " + ns);
count++;
check(count);
}
}
}

Answer

Change

if (s.hasNext() == true) {
    String ns = s.nextLine();
    System.out.println(count + " " + ns);
    count++;
    System.out.print(count);
    check(count);
}

to:

while (s.hasNext()) {
    String ns = s.nextLine();
    System.out.println(count + " " + ns);
    count++;
    System.out.print(count);
    check(count);
}

while loops continues until the data exists, where as if checks for only once.