I am a new Java user. This is my first question. I am just making a fibonacci number generator but got this error:
Exception in thread "main" java.lang.StackOverflowError
at com.intro.javaintro.JavaIntro.fib(JavaIntro.java:11) // This line is repeat 1024 times
Here is my code:
public class JavaIntro {
static int fib(int n) {
int i = 0;
if (n == 1) {
i = 0;
} else if (n == 1) {
i = 1;
} else {
i = fib(n - 1) + fib(n - 2);
}
return i;
}
public static void main(String[] args) {
System.out.println(fib(5));
}
}
Plz help me
stackoverflow error means your recursion isn't ending properly
in your code the first two if statements are supposed to be your exits. since you are checking n==1 twice,
if n = 3
fib(1) and fib(2) will be called fib(1) will be closed but fib(2) wont
fib(2) will call fib(1) and fib(0)
fib(0) will call fib(-1) and fib(-2)...
fibonacci series look sth like this: 1 1 2 3 5 8 13...
considering that you are trying to get the nth fibonacci number your condition should look sth like this
if n is 1 or 2 returns 1
if n is higher than 2 returns sum of n-1 and n-2
your condition should look sth like this
if(n==1||n == 2) {
i = 1;
} else {
i = fib(n - 1) + fib(n - 2);
}