在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 阅读(2057)
评论(2) 编辑 收藏 所属分类:
Data Structure && Algorithm