我正在编写代码来计算 Pi 的值,有时可能需要很长时间才能计算出来。我添加了一个进度条来显示进度,但是代码完全按照我的指示执行,它在计算后打开进度条然后立即关闭它(当值达到 100 时它关闭。)我试图粘贴代码对于进度条进入循环,但很快我意识到解决方案,但创建多个进度条窗口。如果放在计算之前,进度条保持在 0(显然)我在下面显示了我的代码:
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JProgressBar;
import javax.swing.border.Border;
import java.util.Scanner;
public class PicCalc
{
public static void main(String args[])
{
Scanner keyboard = new Scanner(System.in);
double i = 0;
double stage = 1;
int iterations = 1;
int x = 3; //Simply a variable to calculate pi
double y = -1.0; // Another variable for pi
double myPi; //This is my calculation of Pi, don't eat it.
System.out.println("Hello! I calculate Pi and compare it to the acutal value of Pi!");
System.out.println("How many iterations?");
iterations = keyboard.nextInt();
//Calculates Pi
for (i = 1.0; i <= iterations; i++)
{
stage = stage + y/x;
y = - y; //Flips Sign
x+=2;
}
myPi = 4*stage;
System.out.println("My Pi: " + myPi);
//STOP CALCULATING PI
//CALCULATE PERCENT COMPLETE
double percent = 100*(i/iterations);
int intPercent = (int) (percent + 0.5); //Adds .5 in order to round.
//STOP CALCULATING PERCENT COMPLETE
//MAKES LOADING SCREEN
JFrame f = new JFrame("Loading...");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container content = f.getContentPane();
JProgressBar progressBar = new JProgressBar();
progressBar.setValue(intPercent);
progressBar.setStringPainted(true);
Border border = BorderFactory.createTitledBorder("Calcualating...");
progressBar.setBorder(border);
content.add(progressBar, BorderLayout.NORTH);
f.setSize(300, 100);
f.setVisible(true);
//END OF MAKING LOADING SCREEN
//CLOSES LOADING SCREEN WHEN 100% IS ACHIEVED
if (percent >= 100)
{
f.dispose();
}
//END OF CLOSING SCREEN HERE