Harshit Juneja
Harshit Juneja

Reputation: 117

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

Upvotes: 7

Views: 49418

Answers (13)

Caffeine Coder
Caffeine Coder

Reputation: 1146

One of the approaches -

  public static void main(String[] args) {
    Scanner inputScanner = new Scanner(System.in);
    List<String> inputLines = new ArrayList();

    int i=1;
    while(inputScanner.hasNext()) {
        inputLines.add(i+" "+inputScanner.nextLine());
        i++;
    }

    inputLines.stream().forEach(k->System.out.println(k));
}

Upvotes: 0

Arya
Arya

Reputation: 57

public class Solution {

    
    public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    for(int i=1; scan.hasNext() ; 
    System.out.println(i++ +" "+scan.nextLine()));
        
      
    }
}

Upvotes: 0

Chandru
Chandru

Reputation: 1

you can try like this to get desired result:

public class EOF {

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    for(int i =1;scan.hasNext();i++) {
        String line = scan.nextLine();
        System.out.println(i + " " + line);
    }
    scan.close();
}

}

Upvotes: 0

Hetal Rachh
Hetal Rachh

Reputation: 1543

java.util.Scanner.hasNext() basically helps you to read the input. This method returns true if this Scanner has another token of any type in its input. Returns false otherwise. Check below code snippet,

 while(sc.hasNext()) {
      System.out.println(i + " " + sc.nextLine());
      i++;
 }

You can find complete code at below link,

https://github.com/hetalrachh/HackerRank/blob/master/Practice/Java/Introduction/EndOfFile.java

Upvotes: 0

divya
divya

Reputation: 1

Use while instead of if,but recursive version is better.Here is iterative version:

import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
        Scanner sc=new Scanner(System.in);
        {
            int i=0;

          while(sc.hasNext()==true)
            {
                i=i+1;
                 String s=sc.nextLine();
                System.out.println(i+" "+s);

            };
        }
    }
}

Upvotes: 0

worked
worked

Reputation: 5880

Scanner scanner = new Scanner(System.in);
int i = 1;
while(scanner.hasNext()) {
  System.out.println(i + " " + scanner.nextLine());
  i++;
}

Upvotes: 0

Willi Mentzel
Willi Mentzel

Reputation: 29844

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

Upvotes: 9

Here is the error free program.

import java.util.Scanner;

public class Solution {

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

Upvotes: 0

myer
myer

Reputation: 1

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

Upvotes: 0

user3480296
user3480296

Reputation: 11

public static void main(String[] args) {

    List<String> eol = new ArrayList<String>();
    Scanner in=new Scanner(System.in);
    int t=1;
    while(in.hasNext()){

        eol.add(in.nextLine());
    }

    for (String i:eol){

        System.out.println(t+" "+i);
        t++;
    }

}

Upvotes: 0

Suresh Atta
Suresh Atta

Reputation: 121998

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.

Upvotes: 1

Ian2thedv
Ian2thedv

Reputation: 2701

If using recursion is a requirement, you can use a helper function:

static void check(int count) {          
    Scanner s = new Scanner(System.in);
    check(count, s);
} 

static void check(int count, Scanner scanner) {
    if(!scanner.hasNext()) {
        return;
    }
    String ns = scanner.nextLine();
    System.out.println(count + " " + ns);
    check(++count, scanner);
}

Notice how new Scanner(System.in) is only called once.

Upvotes: 1

Ramesh-X
Ramesh-X

Reputation: 5055

Scanner is kind of a BufferedReader (I'm not telling about inheritance or something. I'm telling they both have buffers. Scanner has just a small one). So after you enter text in the Console, those are read() from System.in and stored in the buffer inside the Scanner.

public static void main(String[] args) {          
    Scanner s1 = new Scanner(System.in);
    s1.hasNext();
    Scanner s2 = new Scanner(System.in);
    while(true){
        System.out.println("Read line:: " + s2.nextLine());
    }
}

Use the following input to the Scanner:

line 1
line 2
line 3
line 4

You will get the output:

Read line:: e 1
Read line:: line 2
Read line:: line 3
Read line:: line 4

I think you might know the reason to this output. Some characters of the first line are in the Scanner s1. Therefore don't create 2 Scanners to take input from same Stream.

You can change your code as follows to get required output.

private static Scanner s;

public static void main(String[] args) {
    s = new Scanner(System.in);
    check(1);  // call check method
}

static void check(int count) {
    if (s.hasNextLine()) {
        String ns = s.nextLine();
        System.out.println(count + " " + ns);
        count++;
        check(count);
    }
}

You can use s.hasNextLine() instead of s.hasNext() as you are reading line by line.

No need to use s.hasNextLine()==true as that statement will be true if and only if s.hasNextLine() is true.

You can give EOF character to the console using Ctrl+Z in Windows system and Ctrl+D in Unix. As I know, you can't send EOF character using the output window of NetBeans.

Upvotes: 1

Related Questions