0

Just trying to work out why the output in the console only updates every 10 or so iterations of the loop and not consistently.

    public static void main(String[] args) throws Exception
    {
        for(int i = 0; i <=100;i++)
        {
            System.out.print(i+"% complete");
            Thread.sleep(500);
            System.out.print("\r");
        }
    }
}```
  • Thanks, running it normally in Netbeans. It will output 10% then wait for long and print 34% and so on. How would i omit the linefeed? – Sebastian G Jan 15 '21 at 12:00
  • Okay, but then it appends the output. – Sebastian G Jan 15 '21 at 12:05
  • for(int i = 0; i <=100;i++) { System.out.print(i+"% complete"); Thread.sleep(500); } OUTPUTS: 0% complete 1% complete etc – Sebastian G Jan 15 '21 at 12:08
  • So, instead of appending the output each iteration of the loop, i want it to "update" the output every 0.5 seconds, but the output updates only when the console is refreshed which i don't think is a coding error. – Sebastian G Jan 15 '21 at 12:11
  • Okay, i changed to println, still only appends the output. I think the error is not related to the code, but thanks for assisting. – Sebastian G Jan 15 '21 at 12:13
  • Wait, by "update the output, not append" do you mean something like replacing the current value in the console with the new value? – maloomeister Jan 15 '21 at 12:15
  • I think I understood your issue now. Is [this](https://stackoverflow.com/questions/4573123/java-updating-text-in-the-command-line-without-a-new-line) what you want? – maloomeister Jan 15 '21 at 12:17
  • You probably just need a `System.out.flush();` after printing the percentage. Most terminals and command windows buffer their output. – VGR Jan 15 '21 at 14:23

1 Answers1

-1

Perhaps try replacing System.out.print("\r"); with System.out.print("\n"); to ensure the buffer flushes.

If the \r is important, you can call System.out.flush() at the end to ensure the text is printed to output.

kagama
  • 92
  • 1
  • 7
  • Thanks, the \r is important and sadly System.out.flush() doesn't resolve it. I think the error is to do with my pc or the Netbeans IDE. No worries. – Sebastian G Jan 15 '21 at 12:23