Reputation: 75
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
Reputation: 1581
For eclipse you need to configure the console to interpret the Ascii charaters like so
Upvotes: 2
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:
Upvotes: 2
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