[英]Text-based loading bar when running Java in command prompt?
我只是想知道是否有辦法使用System.out.println();
當我使用批處理文件運行我的程序時,或其他方法來創建一個很酷的加載欄。
這里真正的問題是如何讓這個條看起來好像只打印在一行上。
我不希望它像下面這樣分布在多行上:
[aaaaaccccccccccccccc] 25%
[aaaaaaaaaacccccccccc] 50%
[aaaaaaaaaaaaaaaccccc] 75%
一個保持干凈的地方會讓事情變得更干凈、更友好。
非常感謝,
賈斯蒂安
編輯:
好的。 我設法在這里找到了這個鏈接: 如何為命令行設置動畫? ,但答案是:
在 Java 中有沒有更好的方法來做到這一點?
編輯:
這是我最終的結果:
static final int PROGRESSBAR_LENGTH = 20;
public static void drawProgressBar(int numerator, int denominator) {
int percent = (int) (((double) numerator / (double) denominator) * 100);
String bar = "[";
int lines = round((PROGRESSBAR_LENGTH * numerator) / denominator);
int blanks = PROGRESSBAR_LENGTH - lines;
for (int i = 0; i < lines; i++)
bar += "|";
for (int i = 0; i < blanks; i++)
bar += " ";
bar += "] " + percent + "%";
System.out.print(bar + "\r");
}
private static int round(double dbl) {
int noDecimal = (int) dbl;
double decimal = dbl - noDecimal;
if (decimal >= 0.5)
return noDecimal + 1;
else
return noDecimal;
}
示例輸出:
[||||||||||||||||....] 80%
(. = 空格)
作為打印退格字符的替代方法,您可以使用回車符:13(十進制)、0xD(十六進制)或 \\r(轉義字符)。
共有三項規定:
所以,沿着這些路線的事情:
public static void loadMyProgram() {
while(programStillLoading) {
doSomeLoading();
double loadFraction = howCloseToDone(); // A number between 0 and 1
System.out.print("[");
int i = 0;
for( ; i < (int)(loadFraction * 20); i++)
System.out.print("=");
for( ; i < 20; i++)
System.out.print(" ");
System.out.print("] " + (int)(loadFraction * 100) + "%");
System.out.print((char)13);
//System.out.print((char)0xD); // Same as above, but in hex
//System.out.print("\r"); // Same as above, but as the symbol
}
System.out.println();
}
上面將打印[<bar>] <percent>%
,其中<bar>
是0..p
' =
' 后跟0..(20-p)
' '。 它將保持在一行上。
假設您對負載百分比的計算是單調增加的(換句話說,它不像 Windows 加載欄,在 3 秒內從 20% 到 110% 再到 1%),您不必擔心確保您的下一個輸出等於或長於您之前的輸出,因為這總是正確的。 但是,在這種情況下,您可以在“ %
”之后使用兩個空格來處理它。
我已經使用退格方法完成了這項工作 - 它似乎工作正常。
只需使用System.out.print()
而不是System.out.println()
—— 這樣你就不會得到回車。
您需要跟蹤需要打印多少退格,但它工作正常。
順便說一句 - 要在 java 中打印退格,請使用:
System.out.print("\b");
這可能是一個起點。
用法:
ProgressBar pb = new ProgressBar(10,1);
while (loadingStuff) {
doStuff();
pb.update();
}
pb.finish();
班上:
public class ProgressBar {
private static String[] s;
private int pos, increment, size;
public ProgressBar(int size, int increment) {
this.size = size;
this.increment = increment;
s = new String[size+2];
Arrays.fill(s,"a");
s[0] = "[";
s[size+1] = "]";
}
public void update() {
System.out.println('\r');
if (pos+inc<size+2) {
Arrays.fill(s,pos,pos+inc,"c");
pos += inc;
}
for (String ch : s) {
System.out.print(ch);
}
}
public void finish() {
System.out.println();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.