Fibonacci Java Code: Recursive Example

Here is a Java program example that calculates the Fibonacci sequence using recursion.

public class Fibonacci {
    public static int fibonacci(int n) {
        if (n <= 1) {
            return n;
        } else {
            return fibonacci(n-1) + fibonacci(n-2);
        }
    }

    public static void main(String[] args) {
        int n = 10;
        System.out.println("斐波那契数列前 " + n + " 项为:");
        for (int i = 0; i < n; i++) {
            System.out.print(fibonacci(i) + " ");
        }
    }
}

In the code above, the ‘fibonacci’ method calculates the nth Fibonacci number using recursion. In the ‘main’ method, we can specify the number of terms in the Fibonacci sequence to be calculated and print them out.

bannerAds