|
| 1 | +package com.dataanalyzer; |
| 2 | + |
| 3 | + |
| 4 | +public class ProgressBar { |
| 5 | + private final int width; |
| 6 | + private final char barChar; |
| 7 | + private final char emptyChar; |
| 8 | + private final String format; |
| 9 | + private String currentStatus = ""; |
| 10 | + |
| 11 | + |
| 12 | + public ProgressBar(int width, char barChar, char emptyChar, boolean showPercent) { |
| 13 | + this.width = width; |
| 14 | + this.barChar = barChar; |
| 15 | + this.emptyChar = emptyChar; |
| 16 | + this.format = showPercent ? "\r[%s] %3d%% %s" : "\r[%s] %s"; |
| 17 | + } |
| 18 | + |
| 19 | + |
| 20 | + public ProgressBar() { |
| 21 | + this(50, '█', '░', true); |
| 22 | + } |
| 23 | + |
| 24 | + |
| 25 | + public void update(double progress, String status) { |
| 26 | + if (progress < 0) progress = 0; |
| 27 | + if (progress > 1) progress = 1; |
| 28 | + |
| 29 | + int filledWidth = (int) (width * progress); |
| 30 | + StringBuilder bar = new StringBuilder(); |
| 31 | + |
| 32 | + for (int i = 0; i < width; i++) { |
| 33 | + bar.append(i < filledWidth ? barChar : emptyChar); |
| 34 | + } |
| 35 | + |
| 36 | + currentStatus = status != null ? status : ""; |
| 37 | + |
| 38 | + if (format.contains("%3d")) { |
| 39 | + System.out.printf(format, bar.toString(), (int) (progress * 100), currentStatus); |
| 40 | + } else { |
| 41 | + System.out.printf(format, bar.toString(), currentStatus); |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + |
| 46 | + public void update(double progress) { |
| 47 | + update(progress, currentStatus); |
| 48 | + } |
| 49 | + |
| 50 | + |
| 51 | + public void complete() { |
| 52 | + System.out.println(); |
| 53 | + } |
| 54 | + |
| 55 | + public void complete(String completionMessage) { |
| 56 | + System.out.println(); |
| 57 | + System.out.println(completionMessage); |
| 58 | + } |
| 59 | +} |
0 commit comments