日期:2014-05-20  浏览次数:20905 次

递归算法可以+999 超了这个数就报 StackOverflowError(栈溢出异常)如何解决?
public class Test {

//计算的方法
public static int account(int start,int stop)throws Exception{
return (start!=stop) ? start+=(account(start+1,stop)) : start;
}
/**
* @param args
*/
public static void main(String[] args) {
try {
System.out.println(account(1,9999));
} catch (Exception e) {
e.printStackTrace();
}

}

各位大神帮我看一下??解决了立马结贴

------解决方案--------------------
递归本来就不能写这么多层,你想怎么解决?
------解决方案--------------------
java.lang.StackOverflowError

内存溢出了!因为递归的时候,需要保存处理的东西比较多,申请的内存资源也比较大。

这样你可以使用迭代的方法:
public static int acc(int start, int stop) {
int sum = 0;
int temp = start;
int end = stop + 1;

while (temp < end) {
sum += temp++;
}

return sum;
}