D
D
Dmytro O2016-08-24 10:28:31
Java
Dmytro O, 2016-08-24 10:28:31

How to make a download from flashing dots?

Childish question, but still.
You can implement a loop that displays 3 dots with pauses, then erases the line and everything starts again. Kind of like a download.
How to make the loop infinite (up to a certain point), but after it some actions were performed, by the way, the same System.out.print(); ?
Or how to implement it adequately?
Thanks

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Gornostaev, 2016-08-24
@Metall_fest

public class Main {
    public static boolean running = true; // Флаг активности цикла
    
    public static void main(final String args[]) throws InterruptedException, java.io.IOException {
        new Thread(() -> { // Создаём и запускаем новый поток
             try {
                 Thread.sleep(5000); // Ждём в потоке 5 секунд
             } catch(InterruptedException e) {}
             running = false;
        }).start();
        
        byte[] blankLine = "\r    ".getBytes();
        for(int x = 0; running; x++) {
            // Подготавливаем строку с нужным количеством точек
            String data = "\r" + new String(new char[x % 4]).replace("\0", ".");
            // Стираем вывод предыдущей итерации
            System.out.write(blankLine);
            // Выводим точки
            System.out.write(data.getBytes());
            // Ждём 0.2 секунды, чтобы наш примитивный прогрессбар не мельтешил
            Thread.sleep(200);
            if(x > 3) x = 0;
        }
    }
}

A
artemsee, 2016-08-24
@artemsee

Some such algorithm conditionally comes to mind.

public class Loader {

  private boolean isEnded = false;

  public void load() {
    while(!isEnded) {
      for(int i =0; i < 3; i++) {
        //Выводим точку
        Thread.sleep(1000);
        if(!isEnded) { //Необязательное условие, можно просто дать закончится этому циклу
          break;
        }
      }
      //Тут стираем строку
    }
    Syste.out.print(); //Тут действия после загрузки
  }

  public void stopLoader() {
    this.isEnded = true;
  }

}

When needed, just stop the loop by calling the stopLoader() method.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question