Hey everyone,
I was just wondering if there was a way to use System.out.println();
or other methods to create a cool loading bar when I run my program with a batch file.
The real question here is how I can make this bar appear as if it's printing on only one line.
I don't want it to be spread over multiple lines like below:
[aaaaaccccccccccccccc] 25%
[aaaaaaaaaacccccccccc] 50%
[aaaaaaaaaaaaaaaccccc] 75%
One that stays cleanly in place would make things cleaner and friendlier.
Many thanks,
Justian
EDIT:
Ok. I managed to find this link here: http://stackoverflow.com/questions/60221/how-to-animate-the-command-line, but the answer:
- Is for C++, not Java
- Doesn't seem very efficient in Java, having to backspace each line in a loop?
Is there a better way to do this in Java?
EDIT:
Here's what I ended up going with:
static final int PROGRESSBAR_LENGTH = 20;
public static void drawProgressBar(int numerator, int denominator) {
int percent = (int) (((double) numerator / (double) denominator) * 100);
String bar = "[";
int lines = round((PROGRESSBAR_LENGTH * numerator) / denominator);
int blanks = PROGRESSBAR_LENGTH - lines;
for (int i = 0; i < lines; i++)
bar += "|";
for (int i = 0; i < blanks; i++)
bar += " ";
bar += "] " + percent + "%";
System.out.print(bar + "\r");
}
private static int round(double dbl) {
int noDecimal = (int) dbl;
double decimal = dbl - noDecimal;
if (decimal >= 0.5)
return noDecimal + 1;
else
return noDecimal;
}
Sample output:
[||||||||||||||||....] 80%
(.'s = spaces)