我正在尝试制作这样的进度条
[# ] 10%
[##### ] 50%
[#########] 100%
我尝试了什么
public static void main(String[] args) throws InterruptedException {
String format = "[# ]%d%%\r";
for(int i=0;i<=100;i++){
System.out.print(String.format(format, i));
Thread.sleep(10);
}
}
输出:
[# ] 10%
[# ] 50%
[# ] 100%
问题是我无法根据进度增加 #
计数。
那么我如何移动或增加 # ?
最佳答案
您需要编写一段代码,生成一个以 #
开头、以空格结尾的十个字符的 String
。向此方法传递一个 0 到 100 之间的数字。该方法应将该数字除以 10,并将结果向上舍入。这将为您提供十个字符栏中的 #
字符数:
int numPounds = (pct + 9) / 10;
创建一个循环,附加 '#'
numPounds
次,然后附加 ' '
直到字符串长度为 10。打印 [
... ]
字符之间的结果以完成练习。
private static final StringBuilder res = new StringBuilder();;
static String progress(int pct) {
res.delete(0, res.length());
int numPounds = (pct + 9) / 10;
for (int i = 0 ; i != numPounds ; i++) {
res.append('#');
}
while (res.length() != 10) {
res.append(' ');
}
return res.toString();
}
public static void main (String[] args) throws java.lang.Exception
{
for (int i = 0 ; i <= 100 ; i++) {
Thread.sleep(10);
System.out.print(String.format("[%s]%d%%\r", progress(i), i));
}
}
关于java - 如何在Java控制台应用程序中制作进度条?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31771003/