gpt4 book ai didi

java - java命令行上的非确定性进度条

转载 作者:搜寻专家 更新时间:2023-10-31 19:48:39 26 4
gpt4 key购买 nike

我有一个控制台应用程序,我想在其中的命令行上放置一个不确定的进度条,同时完成一些繁重的计算。目前我只是打印出一个“。”对于类似于以下内容的 while 循环中的每次迭代:

while (continueWork){
doLotsOfWork();
System.out.print('.');
}

这行得通,但我想知道是否有人有更好/更聪明的想法,因为如果循环中有很多迭代,这会变得有点烦人。

最佳答案

这是一个显示旋转进度条和传统样式的示例:

import java.io.*;
public class ConsoleProgressBar {
public static void main(String[] argv) throws Exception{
System.out.println("Rotating progress bar");
ProgressBarRotating pb1 = new ProgressBarRotating();
pb1.start();
int j = 0;
for (int x =0 ; x < 2000 ; x++){
// do some activities
FileWriter fw = new FileWriter("c:/temp/x.out", true);
fw.write(j++);
fw.close();
}
pb1.showProgress = false;
System.out.println("\nDone " + j);

System.out.println("Traditional progress bar");
ProgressBarTraditional pb2 = new ProgressBarTraditional();
pb2.start();
j = 0;
for (int x =0 ; x < 2000 ; x++){
// do some activities
FileWriter fw = new FileWriter("c:/temp/x.out", true);
fw.write(j++);
fw.close();
}
pb2.showProgress = false;
System.out.println("\nDone " + j);
}
}

class ProgressBarRotating extends Thread {
boolean showProgress = true;
public void run() {
String anim= "|/-\\";
int x = 0;
while (showProgress) {
System.out.print("\r Processing " + anim.charAt(x++ % anim.length()));
try { Thread.sleep(100); }
catch (Exception e) {};
}
}
}

class ProgressBarTraditional extends Thread {
boolean showProgress = true;
public void run() {
String anim = "=====================";
int x = 0;
while (showProgress) {
System.out.print("\r Processing "
+ anim.substring(0, x++ % anim.length())
+ " ");
try { Thread.sleep(100); }
catch (Exception e) {};
}
}
}

关于java - java命令行上的非确定性进度条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9302117/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com