【发布时间】:2012-09-28 00:23:56
【问题描述】:
我有一段代码,但我不知道为什么它在线程“main”java.lang.StackOverflowError 中给了我异常。
这是问题:
Given a positive integer n, prints out the sum of the lengths of the Syracuse
sequence starting in the range of 1 to n inclusive. So, for example, the call:
lengths(3)
will return the the combined length of the sequences:
1
2 1
3 10 5 16 8 4 2 1
which is the value: 11. lengths must throw an IllegalArgumentException if
its input value is less than one.
我的代码:
import java.util.HashMap;
public class Test {
HashMap<Integer,Integer> syraSumHashTable = new HashMap<Integer,Integer>();
public Test(){
}
public int lengths(int n)throws IllegalArgumentException{
int sum =0;
if(n < 1){
throw new IllegalArgumentException("Error!! Invalid Input!");
}
else{
for(int i =1; i<=n;i++){
if(syraSumHashTable.get(i)==null)
{
syraSumHashTable.put(i, printSyra(i,1));
sum += (Integer)syraSumHashTable.get(i);
}
else{
sum += (Integer)syraSumHashTable.get(i);
}
}
return sum;
}
}
private int printSyra(int num, int count){
int n = num;
if(n == 1){
return count;
}
else{
if(n%2==0){
return printSyra(n/2, ++count);
}
else{
return printSyra((n*3)+1, ++count) ;
}
}
}
}
驱动代码:
public static void main(String[] args) {
// TODO Auto-generated method stub
Test s1 = new Test();
System.out.println(s1.lengths(90090249));
//System.out.println(s1.lengths(5));
}
。 我知道问题在于递归。如果输入的值很小,则不会发生错误,例如:5。但是当数字很大时,例如 90090249,我在线程“main”java.lang.StackOverflowError 中出现异常。感谢你的帮助。 :)
我差点忘了错误信息:
Exception in thread "main" java.lang.StackOverflowError
at Test.printSyra(Test.java:60)
at Test.printSyra(Test.java:65)
at Test.printSyra(Test.java:60)
at Test.printSyra(Test.java:65)
at Test.printSyra(Test.java:60)
at Test.printSyra(Test.java:60)
at Test.printSyra(Test.java:60)
at Test.printSyra(Test.java:60)
【问题讨论】:
-
很可能是整数溢出。改用 long 。 (并且这里不需要使用递归,虽然如果实现正确,在一定的数字范围内应该不会出现 StackOverflow 错误)。
-
我在这里实际上没有看到递归??你有什么隐瞒吗??你的
printSyra(i,1)方法在哪里? -
@RohitJain
printSyra调用printSyra -
@Pshemo.. 你怎么能假设?它不存在..
-
@RohitJain 检查
printSyra方法的返回值。
标签: java recursion hashmap stack-overflow