1

I'm using the Scanner class as stdin for read input from keybord. I would read token by token the string insert until the end of the line. token are separated by white spaces.

this is my code:

Scanner in = new Scanner(System.in);

    int count=0;
    while(in.hasNextLine()){
        while(in.hasNext()){
            String s=in.next();
            System.out.println(s);
            if(s.equals("\n")) 
             break;
            count++;
        }
        break;
    }
    System.out.println(count);

The problem is that when i press enter, it seems considering it like a white space and it never exit from while block, so it continues to expect another input.

the only way to exit from the while and end the program in Linux is to press ctrl+D (=enter) but i'm searching another way...

I tried to insert an if statement which check if the token is a "\n" but it doesn't work.

Can you help me find a solution to the problem?

2
  • What is the goal of the program ? Commented Jan 25, 2017 at 11:22
  • sorry, the program has to count how many words there are in the string. i know i can do it in other ways like splitting the string, put in array and taking the length of the array, but i'm trying to understand the .hasNext() method... Commented Jan 25, 2017 at 11:34

1 Answer 1

2

The in.hasNextLine() and in.hasNext() methods are blocking ones when used with streams: if there is no new line or new token, they will wait until you write something and press enter again.

If you only want one line you can use something like:

package test;

import java.util.Scanner;

public class Test {

    public static void main(String[] args) {
        int count=0;
        Scanner in =new Scanner(System.console().readLine()); //scanning just one line
        while(in.hasNext()){
            String s=in.next();
            System.out.println(s);
            count++;
        }
        System.out.println(count);
        in.close();
    }

}

Note: If you execute this code from an IDE, there is no console, so System.console() return null. In order to run it from the command line you need to type something like:

$ pwd
/home/user/development/workspace/test/bin
$ ls
test
$ ls test
Test.class
$ java -classpath /home/user/development/workspace/test/bin/ test.Test
Sign up to request clarification or add additional context in comments.

2 Comments

it gives me this exception: Exception in thread "main" java.lang.NullPointerException
I guess you are executing it from an IDE, check my update

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.