Isaiah Mitchell
Isaiah Mitchell

Reputation: 75

Updating java Console without printing new line

So, basically what I want to do is have a percentage. So it goes up 0%, 1% and so on but, instead of having it all printed, I want the %1 percent replaced with 2%. So I know how to do the basic for loop but I don't know how to use \r or \b because in my compiler all I'm getting is it printing it all in one line.

package test;

public class est
{
    public static void main(String[] args) 
    {       
        for(int i = 0; i <= 100; i++ )
        {
            System.out.print("\rPercent = " + i + "%");
        }
    }
}

output:

Percent = 0%
Percent = 1%

...

Percent = 99%
Percent = 100%

So it prints 100 lines; but I only want that information on one line.

Upvotes: 5

Views: 6056

Answers (3)

Java Main
Java Main

Reputation: 1581

For eclipse you need to configure the console to interpret the Ascii charaters like so

enter image description here

Upvotes: 2

GhostCat
GhostCat

Reputation: 140417

The simple answer is: System.out is not an appropriate basis when you strive to provide "enhanced user experience". Maybe in this case, as you can use \r to delete on the same line. But as soon as you need / want to do a println() that context is fixed; and you can't change it anymore.

And even then: "going back" and erasing information can't be done in a way that would work on each platform.

You have three options:

  • simply accept it. In the real world, command line output is often ugly and most people accept that.
  • look into "curses" based libraries, as those allow for "placing" and "resetting" your "cursor". But I actually can't say how platform independent those libraries are.
  • go down the full nine yards and consider creating a real Guide. But of course, that is the most expensive solution to your problem.

Upvotes: 2

Amit Phaltankar
Amit Phaltankar

Reputation: 3424

I tried using '\r' in the sysout and it worked for me in Intellij Idea console & running it from terminal of mac osx.

 public static void main(String[] a) throws InterruptedException {
    int progress = 10;
    for(progress = 10; progress<=100; progress+=10) {
        System.out.print("\rPercent = " + (progress) + "%");
        Thread.sleep(3000);
    }
}

You may want to give it a try. However, I strongly believe it will be dependent upon the underlying console and OS.

Upvotes: 4

Related Questions