【发布时间】:2019-03-27 14:07:28
【问题描述】:
对于一个项目,我正在生成流程日志,它显示当前完成的百分比,但问题是,每个百分比显示相同的百分比可能时间。我想要只打印每个百分比值一次的东西。
public class Progress {
public static void progressPercentage(int done, int total) {
System.out.println();
String iconLeftBoundary = "[";
String iconDone = "*";
String iconRemain = " ";
String iconRightBoundary = "]";
if (done > total) {
throw new IllegalArgumentException();
}
int donePercents = ((100 * done) / total) +1;
StringBuilder bar = new StringBuilder(iconLeftBoundary);
for (int i = 0; i < 100; i++) {
if (i < donePercents)
bar.append( iconDone );
else
bar.append( iconRemain );
}
bar.append(iconRightBoundary);
System.out.print("\r" + bar + " " + donePercents + "%");
if (done == total) {
System.out.println("\n");
}
}
}
这里方法接受参数一个是完成,第二个是total。我正在根据这两个参数计算 %。
Output I am getting:
[*] 1%
[*] 1%
[*] 1%
[*] 1%
[*] 1%
[**] 2%
[**] 2%
[**] 2%
[**] 2%
[**] 2%
Expecting:
[*] 1%
[**] 2%
[***] 3%
[****] 4%
[*****] 5%
【问题讨论】:
-
添加一个检查当前百分比与上次显示的百分比不同的条件怎么样?
-
使方法实例化,而不是静态的,并使用实例变量来存储您之前拥有的百分比。
-
你能举个例子吗?