2
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?

Retsam
  • 30,909
  • 11
  • 68
  • 90

1 Answers1

2

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.

slipperyseal
  • 2,728
  • 1
  • 13
  • 15
  • Ah. So even though PrintWriter is working, I shouldn't rely on it, as it might flush without warning in the middle of my code? – Retsam Oct 30 '12 at 04:19
  • 1
    Yes, you are relying on a side effect that it buffers and how big that buffer is. If one of your requirements is, to buffer all the results before printing, its something you should implement yourself. In your case, for strings a StringBuffer would be ok. For binary data, its common to use a ByteArrayOutputStream. – slipperyseal Oct 30 '12 at 04:24