Aillyn Aillyn - 1 month ago 7
Java Question

How can I print to the same line?

I want to print a progress bar like so:

[# ] 1%
[## ] 10%
[########## ] 50%


But these should all be printed to the same line in the terminal instead of a new one.
What I mean by that is that each new line should replace the previous, it's not about using
print()
instead of
println()
.

How can I do that in Java?

NPE NPE
Answer

Format your string like so:

[#                    ] 1%\r

Note the \r character. It is the so-called carriage return that will move the cursor back to the beginning of the line.

Finally, make sure you use

System.out.print()

and not

System.out.println()