我调试了大半天了,怎么还是解决不了这个异常?请帮忙

chenruoshui 2007-11-19 04:11:24
import java.math.BigInteger; //从java.math中导入BigInteger
import java.util.*; //从java.util中导入ArrayList

/**
*本程序使用任意大的整数,因此
*计算值没有上界,使用ArrayList
*对象代替定长数组缓存计算值。ArrayList
*与数组类似但大小不限。factorial()方法
*声明为同步,这样在多线程程序中也可以安全使用
**/
public class FactorialWithBuffer {
protected static ArrayList table = new ArrayList();//创建缓存
static {//用 !0 = 1 来初始化缓存的第一个元素
table.add(BigInteger.valueOf(1));
}

/**factorial()方法使用缓存在ArrayList的BigInteger*/
public static synchronized BigInteger factorial(int x){
if(x < 0) throw new IllegalArgumentException("x must be non-negative");
for(int size = table.size(); size <= x; size++){
BigInteger lastfact = (BigInteger)table.get(size);
//System.out.println(size);
BigInteger nextfact = lastfact.multiply(BigInteger.valueOf(size));
table.add(nextfact);
}
return (BigInteger)table.get(x);
}
//这个简单的main方法我们可以用于factorial()方法中作为独立的程序
public static void main(String[] args){
for(int i = 0; i <=9; i++)
System.out.println(i + "!=" + factorial(i));
}
}
...全文
121 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
whfbbs 2007-11-19
  • 打赏
  • 举报
回复
泛型

protected static ArrayList<Object> table=new ArrayList<Object>();
//protected static ArrayList table = new ArrayList();//创建缓存
lovewhzlq 2007-11-19
  • 打赏
  • 举报
回复
import java.math.BigInteger; //从java.math中导入BigInteger
import java.util.*; //从java.util中导入ArrayList

/**
* 本程序使用任意大的整数,因此 计算值没有上界,使用ArrayList 对象代替定长数组缓存计算值。ArrayList
* 与数组类似但大小不限。factorial()方法 声明为同步,这样在多线程程序中也可以安全使用
*/
public class FactorialWithBuffer {
protected static ArrayList table = new ArrayList();// 创建缓存
static {// 用 !0 = 1 来初始化缓存的第一个元素
table.add(BigInteger.valueOf(1));
}

/** factorial()方法使用缓存在ArrayList的BigInteger */
public static synchronized BigInteger factorial(int x) {
BigInteger nextfact;
if (x <= 0)
throw new IllegalArgumentException("x must be non-negative ");
else{
BigInteger lastfact = (BigInteger)table.get(x-1);
// System.out.println(size);
nextfact = lastfact.multiply(BigInteger.valueOf(x));
table.add(nextfact);
}
return (BigInteger)table.get(x);
}

// 这个简单的main方法我们可以用于factorial()方法中作为独立的程序
public static void main(String[] args) {

for (int i = 1; i <= 9; i++)
System.out.println(i + "!= " + factorial(i));
}
}


这样不就得了

62,623

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧