public static void main(String[] args) {
one();
System.out.println();
}
public static void one() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number:");
int i = sc.nextInt();
for (int j=0; j<i; j++) {
System.out.println(fibonacci(j));
}
}
public static int fibonacci(int num){
if (num == 1) {
return 0;
}
else if (num == 2 || num == 3){
return 1;
}
else {
return fibonacci(num-1) + fibonacci(num-2);
}
}
When I run this will get Exception in thread "main" java.lang.StackOverflowError but if I change one() to
public static void one() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number:");
int i = sc.nextInt();
System.out.println(fibonacci(j));
}
I wont get error, even I just enter 1, could I ask why?
You don't handle the case of num == 0
, so when you call fibonacci(0)
the recursion never ends, leading to StackOverflowError
when the stack is full.
You can solve it by changing the range of your loop
for (int j=1; j<i; j++) {
System.out.println(fibonacci(j));
}
or by changing the stopping condition of your recursive method:
public static int fibonacci(int num) {
if (num <= 1) {
return 0;
}
else if (num == 2 || num == 3){
return 1;
}
else {
return fibonacci(num-1) + fibonacci(num-2);
}
}
That said, it would be much more efficient to store the intermediate results of fibonacci(i)
, and re-use them when calculating fibonacci(n)
for n > i
(instead of making unnecessary expansive recursive calls).
In the for-Statement you start with 0. This is the first Input to fibonacci-Funktion. Try:
public static void one() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number:");
int i = sc.nextInt();
for (int j=1; j<i; j++) {
System.out.println(fibonacci(j));
}
I think you missed to handle the zero. Just try the following loop,
for (int j=1; j<=i; j++) {
System.out.println(fibonacci(j));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.