我目前正在編寫計算PI和E到第n項的代碼。我在TermsJTextField中輸入一個數字,選擇PI或E單選按鈕(一次只能有一個按鈕處於活動狀態),按下計算,它應該顯示適當的答案。然而,當我按下calculate時,應用程序會處於掛起狀態,並且沒有任何按鈕會響應,即使是x按鈕。答案從不顯示。這個Java應用程序爲什麼掛起/凍結?
這是代碼。我已經收窄到讓我頭疼的部分:
private void CalculateJButtonActionPerformed(java.awt.event.ActionEvent evt) {
final double MAX_VALUE = 10000; //Max value
double Start, End; //Star and end time
BigDecimal result = new BigDecimal ("0"); // Constants for result
BigDecimal Error = new BigDecimal ("0"); // And Error
DecimalFormat integerFormatter = new DecimalFormat("#0.");
Start = System.currentTimeMillis();
int Terms;
int count = 1;
boolean PIchecked = PiJRadioButton.isSelected();
boolean Echecked = EJRadioButton.isSelected();
double PI = 0;
double E = 1;
try
{
Terms = Integer.parseInt(TermsJTextField.getText());
if ((Terms <= 2) || (Terms >= 10000)) // This checks for the number of terms
{
throw new NumberFormatException();
}
else
{
if (PIchecked) // If Pi butoon is selected, do the following calculation
{
for (int i =1 ; 1 <= (Terms);i++)
{
count++;
result = result.add(new BigDecimal (Math.pow((-1.0),count)/(2*i-1)));
}
EJRadioButton.setSelected(false);
result = result.multiply(new BigDecimal (4.0));
Error = new BigDecimal(Math.abs(PI-result.doubleValue())/PI * 100.0);
}
else if (Echecked) // This calculates nth term for E
{
result = new BigDecimal("0");
long factorial = 1L;
for (int i = 1; i < Terms ; i++)
{
factorial *= i;
result = result.add(new BigDecimal(1.0/factorial));
}
result = result.add(new BigDecimal(1L));
Error = new BigDecimal(Math.abs(E-result.doubleValue())/E * 100.0);
PiJRadioButton.setSelected(false);
}
End = System.currentTimeMillis(); //Time in ms to calculate the answer
//Output
DecimalFormat Number = new DecimalFormat("#####0.##");
if (PIchecked)
{
EJTextField.setText("");
PIJTextField.setText(String.valueOf(result));
ErrorJTextField.setText(String.valueOf(Error + "%"));
}
else
{
PIJTextField.setText("");
EJTextField.setText(String.valueOf(result));
ErrorJTextField.setText(String.valueOf(Error + "%"));
}
PrintJButton.setEnabled(true);
PrintJMenuItem.setEnabled(true);
TimeJTextField.setText(String.valueOf(End-Start));
}
}
catch(NumberFormatException exp)
{
Object ERROR_MESSAGE = null;
JOptionPane.showMessageDialog(null, "Don't be silly; Enter a vaule between 2 and 10000",
"Input Error", JOptionPane.ERROR_MESSAGE);
TermsJTextField.selectAll();
TermsJTextField.setText("");
TermsJTextField.requestFocus();
}
}
你用調試器或分析器找出程序花費其大部分時間?無響應的部分可能只是試圖在應用程序線程上做太多。 – Carcigenicate
還要仔細看看你的循環......尤其是在完成條件下 – IEE1394
看來你的代碼運行過多迭代可能是無限的,應該有一箇中斷或限制條件來停止執行 –