Note that there are some explanatory texts on larger screens.

plurals
  1. POText-based loading bar when running Java in command prompt?
    text
    copied!<p>I was just wondering if there was a way to use <code>System.out.println();</code> or other methods to create a cool loading bar when I run my program with a batch file.</p> <p>The real question here is how I can make this bar appear as if it's printing on only one line.</p> <p>I don't want it to be spread over multiple lines like below:</p> <pre><code>[aaaaaccccccccccccccc] 25% [aaaaaaaaaacccccccccc] 50% [aaaaaaaaaaaaaaaccccc] 75% </code></pre> <p>One that stays cleanly in place would make things cleaner and friendlier.</p> <p>Many thanks,</p> <p>Justian</p> <p><strong>EDIT:</strong></p> <p>Ok. I managed to find this link here: <a href="https://stackoverflow.com/questions/60221/how-to-animate-the-command-line">How to animate the command line?</a>, but the answer:</p> <ol> <li>Is for C++, not Java</li> <li>Doesn't seem very efficient in Java, having to backspace each line in a loop?</li> </ol> <p>Is there a better way to do this in Java?</p> <p><strong>EDIT:</strong></p> <p>Here's what I ended up going with:</p> <pre><code>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 &lt; lines; i++) bar += "|"; for (int i = 0; i &lt; 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 &gt;= 0.5) return noDecimal + 1; else return noDecimal; } </code></pre> <p>Sample output:</p> <p><code>[||||||||||||||||....] 80%</code> (.'s = spaces)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload