PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, October 29, 2022

[FIXED] How to use hasNext() from the Scanner class?

 October 29, 2022     eof, java, java.util.scanner     No comments   

Issue

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


Answered By - Willi Mentzel
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing