Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scanner HasNextLine always returns false

I'm facing this weird problem with Scanner.hasNextLine(). I'm not used with the Scanner class but I'm used to use Scanner.hasNextLine() as a condition for a loop to get continuously user's input but in this part of code it always returns false !

public static void main(String[] args) throws IOException {
    String s = "";
    Scanner ssc = new Scanner(System.in);
    Client cli = new Client();
    cli.HLO();
    Thread t = new Thread(new ThreadMessage(cli));//Thread that asks user for input using Scanner and closing it then
    t.start();
    boolean b = ssc.hasNextLine();
    while (true) {
        b = ssc.hasNextLine();
        System.out.println(b);
        if (b) {
            s = ssc.nextLine();
            System.out.println("you wrote" + s);
            cli.dp.setData(s.getBytes());
            cli.ds.send(cli.dp);
        }
    }
}

and as is an input I only have a loop of lines with the word false

Does anybody have an idea why it behaves so?

EDIT: Seems that the errors comes froms HLO function that uses another Scanner I removed it and it words properly now.

like image 491
user3129482 Avatar asked Nov 02 '22 01:11

user3129482


1 Answers

Try to use the .hasNext() method instead of using the .hasNextLine() method.
You are having problems because the .hasNextLine() method returns true if there is another line in the input of this scanner. But the .hasNext() method returns true if this scanner has another token in its input.

Refer : http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

like image 55
Shreyos Adikari Avatar answered Nov 15 '22 05:11

Shreyos Adikari