0

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"

Alexei
  • 14,350
  • 37
  • 121
  • 240
  • 3
    `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) – Aaron Aug 29 '20 at 22:52

2 Answers2

2

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

Liel Fridman
  • 1,019
  • 7
  • 11
1

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)

beastlyCoder
  • 2,349
  • 4
  • 25
  • 52
  • Your answer doesn't point out *why* OP's code isn't working. It's been pointed out in the comments, but maybe you could add it to your sesponse for completeness' sake? –  Aug 29 '20 at 23:01