posts - 97,  comments - 93,  trackbacks - 0

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

FeedBack:
# re: 求任意正整数的阶乘
2006-11-15 22:48 | mxtk
hao  回复  更多评论
  
# re: 求任意正整数的阶乘
2006-11-15 22:49 | mxtk
tai hao le  回复  更多评论
  

只有注册用户登录后才能发表评论。


网站导航:
 
<2006年7月>
2526272829301
2345678
9101112131415
16171819202122
23242526272829
303112345




常用链接

留言簿(10)

随笔分类(95)

随笔档案(97)

文章档案(10)

相册

J2ME技术网站

java技术相关

mess

搜索

  •  

最新评论

阅读排行榜

校园梦网网络电话,中国最优秀的网络电话