'Add a loading effect with progress

Often when we download something use the terminal or the command prompt, we get a progress like this:

----------10%

after a while

------------------------------------------33%

after a while

---------------------------------------------------------48%

and then this continues until it is 100% in the same line. Even I tried to do something like this, but ended up getting a result like this:

-1%-2%-3%-4%-5%-6%-7%-8%-9%-10%-11%-12%-13%-14%-15%-16%-17%-18%-19%-20%-21%-22%-23%-24%-25%-26%-27%-28%-29%-30%-31%-32%-33%-34%-35%-36%-37%-38%-39%-40%-41%-42%-43%-44%-45%-46%-47%-48%-49%-50%-51%-52%-53%-54%-55%-56%-57%-58%-59%-60%-61%-62%-63%-64%-65%-66%-67%-68%-69%-70%-71%-72%-73%-74%-75%-76%-77%-78%-79%-80%-81%-82%-83%-84%-85%-86%-87%-88%-89%-90%-91%-92%-93%-94%-95%-96%-97%-98%-99%-100%

So, this happens after every progress. This is what I did to do so:

for (progress in 1..100){
   print("-$progress%")
   Thread.sleep(100)
}

or in java:

for(int i = 0; i < 100; i++){
   System.out.print("-" + i + "%");
}

So, how can I achieve something like that with the progress being in a single line?



Solution 1:[1]

Try this here a string is repeated n times, and then it is printed along with its percentage covered.

"\r" is a escape sequence which brings back the cursor to the starting point of the current line.

import java.lang.Thread;

class Main {
    public static void main(String args[]) {
        try {
            for (int i = 0; i <= 100; i++) {
                System.out.print("\r" + "-".repeat(i) + i + "%");
                Thread.sleep(50); // 50 millisecond
            }
            System.out.println();
        } catch (Exception e) {
            System.err.println(e);
        }
    }
}

Here's the kotlin code:

fun main() {
    for( i in 1..100 ){
       print("\r ${"=".repeat(i)}> $i%");
       Thread.sleep(50);
    }
    println()
}

Output JAVA:

JAVA OUTPUT

Output KOTLIN:

KOTLIN OUTPUT

Solution 2:[2]

If you would like to display the loading bar uninterrupted and on one line, you can try using this approach:

        for (int i = 1; i <= 100; i++) {
            Thread.sleep(300);
            String backspaceCharacter = "\b";

            int numberOfCharactersToDelete =  2;
            if (i / 10 > 0) numberOfCharactersToDelete++;
            System.out.print(backspaceCharacter.repeat(numberOfCharactersToDelete) + "-" + i + "%");
        }

It works by printing a backspace character for deleting the previous x%. There are definitely better ways to do this, but I find this way to be the easiest. Warning: I didn't bug check this, it should be used more like an inspiration than a complete solution. It also may not work in some consoles.

Solution 3:[3]

As other answers show, in general the simple way is to print a carriage return (\r) without a newline (\n): this moves the cursor back to the start of the same line, after which you can overwrite the existing line with a new one.

This only works if the new version of the line is at least as long as the previous one — or you append spaces to overwrite the rest.

If you want to do anything more powerful, the usual way is to print ANSI escape codes.?Most modern terminal programs will understand these; they let you move the cursor directly to any point in the window, clear a line or even the whole screen, and use colours and effect such as bold, italic, and reverse video.

(Traditionally, you'd have to determine the current terminal type, and then look up the escape sequences it supported in a termcap database — but these days that's overkill unless you need maximal compatibility, and the ANSI escapes are well supported.)

Alternatively, you can use a library which does all that for you; see this question.

Solution 4:[4]

I can answer this for Java.

Assuming you want each progress printed on a new line, use: System.out.println(); instead. Or add \n where relevant.

Also assuming you want to increase the quantity of dashes with each incremental progress point, you'd have to add an inner for loop to repeat the printing of the "-" multiple times, something like this?

for (int i = 0; i < 100; i++) {
    TimeUnit.SECONDS.sleep(1);
    for (int j = 0; j < i; j++) {
        System.out.print("-");
    }
    System.out.print(i + "%\n");
}

Example output

Or if you want it to look like it's clearing the line and then reprinting the new progress bar, to make it look dynamic, you could try something like this (add more or less \n characters to increase or decrease gap):

for (int i = 0; i < 100; i++) {
    TimeUnit.SECONDS.sleep(1);
    System.out.print("\n\n\n\n\n\n\n\n\n\n\n\n\n");
    for (int j = 0; j < i; j++) {
        System.out.print("-");
    }
    System.out.print(i + "%\n");
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Fambo
Solution 3 gidds
Solution 4