Alexei
Alexei

Reputation: 15674

Scanner.hasNextLine - always true

I need to read data from standard input. And I want to print it to standard output. I use Scanner for this:

import java.util.Scanner;
 public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder sb = new StringBuilder();
        int countLines = 1;
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            sb.append(countLines).append(" ").append(line);
        }
        System.out.println("finish");
        System.out.println(sb.toString());
        scanner.close();
    }

I input this data:

Hello world
I am a file
Read me until end-of-file.

But hasNextLine()) is always true. And as result never print "finish"

Upvotes: 0

Views: 650

Answers (2)

beastlyCoder
beastlyCoder

Reputation: 2401

There is no condition in which the loop will be false, it'll read the lines forever and ever. Consider adding a stop keyword like "stop"

while(scanner.hasNextLine()) 
{
    String line = scanner.nextLine(); 
    if(line.equalsIgnoreCase("stop")) 
    {
        break; 
    }
    //whatever else you have in the loop
}

Unless you stop it, it'll always be true. As pointed out by @Aaron

Scanner.hasNextLine() blocks waiting for a new line, it will only return false if you close the stream (using Ctrl-Z or D as Liel mentions in his answer)

Upvotes: 1

Liel Fridman
Liel Fridman

Reputation: 1198

Your code seems to work fine. Are you sure you output EOF correctly? Try Ctrl+D (Cmd+D on Mac) or Ctrl+Z on Windows, as mentioned here: How to send EOF via Windows terminal

Upvotes: 2

Related Questions