javajava.util.scannereof

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);
        }
    } 
}

Solution

  • Your code does not work because you create a new Scanner object in every recursive call. You should not use recursion for this anyways, do it iteratively instead.

    Iterative version

    public class Solution {
    
        public static void main(String[] args) {
    
            Scanner s = new Scanner(System.in);
            int count = 1;
    
            while(s.hasNext()) {
                String ns = s.nextLine();
                System.out.println(count + " " + ns);
                count++;
            }
        }
    }
    

    Recursive version

    public class Solution {
    
        private Scanner s;
    
        public static void main(String[] args) {
    
            s = new Scanner(System.in); // initialize only once
            check(1);
        }
    
        public static void check(int count) {
            if(s.hasNext()) {
                String ns = s.nextLine();
                System.out.println(count + " " + ns);
                check(count + 1);
            }
        }   
    }