首先是最简单的方式

 1 public class Fabonacci {
 2     //1 1 2 3 5 8...
 3         static int i = 0;
 4     static int j = 0;
 5     static int f(){
 6         if(j==0){
 7             j = 1;
 8             return 1;
 9         }
10         int r = i + j;
11         i = j;
12         j = r;
13         return r;
14     }
15     public static void main(String[] args) {
16         for (int i = 0; i < 18; i++) {
17             System.out.print(f()+" ");
18         }
19     }
20 }            

输出如下:

1 1 2 3 5 8 13 21 34 55 

 

然后是使用递归

package com.knowind;

public class Fabonacci {
    //1 1 2 3 5 8...
    int count = 0;
    Integer next(){
        return g(count);
    }
    int g(int count){
        this.count++; //
        if(count < 2){
            return 1;
        }
        //0>1 1>1 2>2 3>3 4>5 5>8
        return g(count-1)+g(count-2);//前一次的次数加上前前一次的次数
    }
    public static void main(String[] args) {
        Fabonacci f = new Fabonacci();
        for (int i = 0; i < 10; i++) {
            System.out.print(f.next()+" ");
        }
    }
}

输出:

1 1 2 8 10946 Exception in thread "main" java.lang.StackOverflowError
    at com.knowind.Fabonacci.g(Fabonacci.java:15)
    at com.knowind.Fabonacci.g(Fabonacci.java:15)

来看看为什么会出现这样的情况。事实上,拿 this.count = 8 来举例,刚进来 g( int count )方法, this.count 便 this.count++ 变成了 this.count = 9,随后 ,在 return 的时候,又调用 g( count-1 ) 即 g( 8 )!这不就是陷入了死循环吗?

那么怎么修正呢?

public class Fabonacci {
    //1 1 2 3 5 8...
    int count = 0;
    Integer next(){
        return g(count++);
    }
    int g(int count){
//        this.count++; 
        if(count < 2){
            return 1;
        }
        //0>1 1>1 2>2 3>3 4>5 5>8
        return g(count-1)+g(count-2);//前一次的次数加上前前一次的次数
    }
    public static void main(String[] args) {
        Fabonacci f = new Fabonacci();
        for (int i = 0; i < 10; i++) {
            System.out.print(f.next()+" ");
        }
    }
}

题外话:g( count++) 先为方法形参赋值再对 count+1,这一点和 g( ++count ) 情形相反。

输出如下:

1 1 2 3 5 8 13 21 34 55