Retsam
Retsam

Reputation: 33389

Java: PrintStream unexpectedly autoflushing

import java.io.PrintStream;
import java.util.Scanner;
public class OutputTest
{

    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);
        PrintStream out = new PrintStream(System.out); 
        while(true) 
        {
            int in = scan.nextInt();
            if(in == 0) break;
            System.out.println(in*in);
        }
        out.flush();
    }

}

I'm expecting this program to take a list of numbers, one per line, and then when it hits a zero, print all of their squares, one per line. Instead, it's just echoing each number I type with the square.

Ideally, I'd actually include the line:

System.setOut(out);

and then write the rest of my program normally (except with the flush at the end), but this had the same result of echoing right away.

However, changing the PrintStream to a PrintWriter did make this work as expected, however I cannot do System.setOut since PrintWriter doesn't extend OutputStream.

Why isn't this behaving as I expect?

Upvotes: 2

Views: 471

Answers (1)

slipperyseal
slipperyseal

Reputation: 2778

flush() on any stream or writer means "flush if there is anything to flush". It is not expected behavior that any stream or writer will buffer before being manually flushed. You could wrap the output stream with a buffered stream, but it will also flush when the buffer size you specify is full. The easiest solution in your case is to write to a StringBuffer and then print this on receiving the zero.

Upvotes: 2

Related Questions