Fibonacci sequence will not print anything but the number that is inputted by the user

Viewed 84

Here is my main method, I am trying to call the Fibonacci sequence to tell me what number would be at the location the user inputs:

import java.util.Scanner; //import Scanner

public class Main {
    public static void main(String[] args) {
         
       System.out.println("enter number");
       Scanner input = new Scanner(System.in); 
       int n = input.nextInt();
         
       Fibonacci fibonacci_test = new Fibonacci();
       fibonacci_test.Recursivefibonacci(n);
         
    }
}

Here is my Fibonacci code that I have:

public class Fibonacci {
//Fn=F(n-1)+F(n-2)
    
        
    //The recursive Fibonacci method 
    public int Recursivefibonacci(int n) {
       
        if(n==0) {
            return 0;
        } if(n==1) {
            return 1;
        }else {
            
        int fib = Recursivefibonacci(n-1)+Recursivefibonacci(n-2);
        return fib;
        }
            
    }
}

I cannot get this thing to print anything. How can I fix this?

3 Answers

It's because you're not printing anything else. Your method doesn't print anything (just returns a value), and your main doesn't print anything (aside from "enter number").

You can try changing: fibonacci_test.Recursivefibonacci(n); to println (fibonacci_test.Recursivefibonacci(n));

It would be more appropriate to return Recursivefibonacci(n-1)+Recursivefibonacci(n-2);rather than storing it in a variable.

I did this in python, you can have a look, try to adapt it to java, this might help you. Recursivity can be a headache but seems good.

def fib(n):
    if n == 0:
        return 0
    if n <= 1:
        return 1
    res = (fib(n-1)+ fib(n-2))
    return res

/////// Probably your code will look somehow like this:

public int Recursivefibonacci(int n) {
    if(n == 0){
       return 0;

}
if(n <= 1) {
   return 1;
    } 

    int fib = Recursivefibonacci(n-1)+Recursivefibonacci(n-2);
    return fib;
        
}

Try it! and let me know if it worked.

Related