# Thread: Need Help - StackOverflowError - Fibonacci

1. Member
Join Date
Apr 2011
Posts
2
Rep Power
0

## 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."

Java 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.

2. 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?

Java 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.
Last edited by sunde887; 04-13-2011 at 03:59 AM.

3. Member
Join Date
Apr 2011
Posts
2
Rep Power
0
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.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•