JDK 1.0+:ASCII进度指示器

123 阅读1分钟

这个例子将一个进度指示器实现为一个旋转的动画人物。


public class Progress {

    private int counter = 0;
    private char sequence[] = {'-','\\','|','/'};

    public void showProgress(){
        counter++;
        int slot = counter % sequence.length;
        char current = sequence[slot];
        System.out.print(current);
        //the backspace character
        System.out.print("\b");
    }    
}

下面的测试将显示一个旋转的字符,持续5秒。该动画在你的IDE或单元测试中可能不工作,但在控制台中应该工作。


public class ProgressTest {
    @Test
    public void rotate(){
        var progress = new Progress();
        for (int i = 0; i < 20; i++) {
            progress.showProgress();
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
            }
        }
    }
}