Need Help - StackOverflowError - Fibonacci

• 04-13-2011, 02:26 AM
ausglanville
Need Help - StackOverflowError - Fibonacci
I'm creating a Fibonacci sequence for a program. The instructions are as follows: "Write a recursive method to compute a fibonocci series. Start at a user supplied starting point and continue 10 places."

Code:

```import javax.swing.JOptionPane; public class Fibonacci {  static String series = "";  static String input = "";  public static void main(String[] args)  {   input = JOptionPane.showInputDialog(null, "Enter an integer.");   int start = Integer.parseInt(input);   fib(start, 0);   JOptionPane.showMessageDialog(null, "The series is \n" + series);  }  /** Computes a fibonocci series starting at a user supplied integer and continuing 10 places. */  public static String fib(int x, int y)  {   int i = 0;   int result = 0;   if(i < 2)   {   result = x;   y = x;   }   else   {   result = x + y;   y = x;   x = result;   }  [B] series += ", " + result;[/B]   i++;    if(i < 10)     fib(x,y);   return series;  } }```
When compiled, the method shows no errors. However, when tested, the bolded line returns the following error: "java.lang.StackOverflowError: null(in java.lang.Stringbuilder)"

As you can tell, I'm quite new to java. I don't know if I'm just not understanding the problem, or if I am, but just going about it the wrong way. Any help is appreciated.
• 04-13-2011, 02:37 AM
Fubarable
You've got recursion gone wild -- it never stops til you run out of memory. Rethink your logic.
• 04-13-2011, 02:54 AM
sunde887
It may help to forget about producing the series for now and just produce the sum of the fibbonaci series as an integer result. Once you do that it may be easier to build the string representing the series.

Here are some things to think about when working on recursion.

1) you should have a termination condition, if this condition is met it should produce the final answer.
2) if the termination condition is not met it should preform a recursive call.

How well do you understand recursion?

Code:

```public static int fact(int n){   if(n == 1){ //termination condition     return 1;   }   else{ //termination condition not met     return n * fact(n - 1);   } }```
This is a recursive call to find the factorial of some number, perhaps it will help you.
• 04-13-2011, 03:43 AM
ausglanville
I found a way to fix it, although I don't quite know if it is the most efficient way. When I declared i and result, both were within the fib method. So each time the fib method is called, i and result are reset, therefore i never meets the i >= 10 exit condition and the loop runs until it runs out of memory. By declaring them as static variables outside of all methods, the problem is fixed.