Exception in thread “main” java.lang.StackOverflowError

J'ai un bout de code et je ne pouvais pas comprendre pourquoi il me donne de l'Exception in thread "main" java.lang.StackOverflowError.

C'est la question:

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.

Mon Code:

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) ;

            }

    }


}
}

Code de pilote:

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));
}

.
Je sais que le problème se trouve avec la récursivité. L'erreur ne se produit pas si l'entrée est une petite valeur, exemple: 5. Mais quand le nombre est énorme, comme 90090249, je suis l'Exception dans le thread "main" java.lang.StackOverflowError. Merci à tous pour votre aide. 🙂

J'ai presque oublié le msg d'erreur:

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)
Les plus susceptibles de dépassement d'entier. L'utilisation à long à la place. (Et il n'est pas nécessaire d'utiliser la récursivité ici, même si mettre en œuvre correctement, il ne devrait pas être StackOverflow d'erreur pour une certaine gamme de nombre).
Je n'ai pas vraiment voir une récursion?? Vous vous cachez quelque chose?? où est votre printSyra(i,1) méthode?
printSyra appelle printSyra
Comment pouvez-vous supposer que?? Son pas là..
vérifier les retours de printSyra méthode.

OriginalL'auteur Ray.R.Chua | 2012-10-07