Search code examples
javadelayloading

Is there any way to make a program that repeats itself on the same row, while also erasing what it wrote before?


I'm trying to make a program that makes 3 dots "..." appear one by one and then start from the beginning on the same row; something like this:

Phase 1: .
Phase 2: ..
Phase 3: ...
Phase 4: .
Phase 5: ..

and so on.

enter code here


    String text2 = "..." + "\n";
    for (int i = 0; i <= 3; i++) {

        for (int j = 0; j < text2.length(); j++) {
            System.out.print("" + text2.charAt(j));
            try {
                Thread.sleep(300);
            } catch (InterruptedException ex) {
                Thread.currentThread().interrupt();
            }

        }
    }

I've tried this but it doesn't quite do it...


Solution

  • You can print a backspace \b as long as the dots like so:

    public static void main(String[] args)
        {
            String text2 = "...";
            for (int i = 0; i <= 3; i++) 
            {
                for (int j = 0; j < text2.length(); j++) {
                    System.out.print("" + text2.charAt(j));
                    try {
                        Thread.sleep(300);
                    } catch (InterruptedException ex) {
                        Thread.currentThread().interrupt();
                    }
                }
                System.out.print("\b".repeat(text2.length())); //Java 11
            }
        }
    

    Also remove the new line in your string since it will cause the dots to print on separate lines.