在Java中,我們只要利用BigInteger類,可以完成同樣功能;這里也測試了異常以及Dialog的產生。
開發環境:Windows Server 2003 Standard Edition SP1, J2SDK 1.5.0_06, Eclipse 3.1.2
源代碼如下:
//Factorial.java
import java.math.BigInteger;
import javax.swing.*;
/**
* 計算任意正整數的階乘
*
*
*/
public class Factorial {
public static void main(String[] args) {
BigInteger x = BigInteger.valueOf(1); //存儲結果
int num = 1; //待計算的整數
String s = null;
boolean correct = false;
do {
try {
s = JOptionPane.showInputDialog(null, "請輸入要計算的數(正整數):");
if (s == null)
break;
else {
num = Integer.parseInt(s);
if (num < 0)
throw new IllegalArgumentException();
else correct = true;
}
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "數據格式錯誤!");
continue;
} catch (IllegalArgumentException e) {
JOptionPane.showMessageDialog(null,"請輸入一個正整數!");
continue;
}
break;
} while (true);
if (correct == true) {
for (int i = 1; i <= num; i++)
x = x.multiply(BigInteger.valueOf(i));
JTextArea textArea = new JTextArea(x.toString(), 5, 30);
textArea.setEditable(false);
textArea.setLineWrap(true);
Object[] object = {num + " ! : ",new JScrollPane(textArea)};
JDialog dialog = new JOptionPane(object).createDialog(null,"階乘的結果");
dialog.setVisible(true);
}
System.exit(0);
}
}
運行結果如下:
posted on 2006-07-22 17:21
wqwqwqwqwq 閱讀(2064)
評論(2) 編輯 收藏 所屬分類:
Data Structure && Algorithm