How can I make a line display in my command-line java program without displaying a new line?

I am making a java command line program.

How to change the contents of a string that I have already displayed?

So, for example, I could display:

Status: 0%
Status: 2%
...
Status: 50%

Instead of continuing to press each new line, I just change the contents of the existing line, so% done changes in place.

I have seen some console programs do this before, so how can I do this in java?

+4
source share
2 answers

In most cases, you can print a carriage return ( \r ) rather than a new line ( \n ). It depends on the terminal supporting it, which is most important. \r moves the cursor back to the beginning of the line.

EDIT: Obviously, use System.out.print , not System.out.println (or just use the regular form, not ln , the output method you use) - since ln suffix means your text will be automatically followed new line.

Example:

 for (n = 10000; n < 10010; ++n) { System.out.print(String.valueOf(n) + "\r"); } System.out.println("Done"); 

When this ends, you will probably get this on the console screen:

 Done0 

... since "Finish" is shorter than the longest previous thing that you output, and therefore does not completely overwrite it (hence, 0 at the end remaining from "10010"). So, the lesson: keep track of the longest entry and rewrite it with spaces.

+3
source

Take a look at this example .

Work code:

 public class progress { public static void main(String[] args) throws InterruptedException { for (int i = 0; i <= 100; i++) { Thread.sleep(30); System.out.print("\rSTATUS: "+i+" % " ); } } } 

Tip. For more progress indicators on Google - java console

+2
source

All Articles