为什么我的函数会出现无限循环?

Why do I get an endless loop in my function?

好的,我正在尝试编写一个程序来输出每个斐波那契数。然而,我的数字将始终从 fib(2) 开始,我将使用 next() 来获取下一个斐波那契数。

public class Fibonacci {
static int NextCounter = 2; // fib(2)
public static void main(String[] args) {
    // TODO Auto-generated method stub
    System.out.println("Enter your number!");
    try {
        FibonacciPrint(System.in.read());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public static void FibonacciPrint (int a){
    for(int i = 0 ; i < a ; i++ ){ 
        System.out.println(next()); // Will never stop? 
    }
}

private static int next() {
    int result = fibo(NextCounter);
    NextCounter += 1;
    return result; 
}

private static int fibo (int n){
    if( n == 1 || n == 2)
    {
        return 1;
    }

    return fibo(n-1) + fibo (n-2);
}

}

所以我期望 for 循环会在 i 等于 a 时停止。正如您可能已经知道的那样,它不会。为什么 ? next() 和 fibo() 工作正常。谢谢你的帮助。

我在 运行 一秒钟后停止后的结果:

Enter your number!
5 // Input
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181
6765
10946
17711
28657
46368
75025
121393
196418
317811
514229
832040
1346269
2178309
3524578
5702887
9227465
14930352
24157817
39088169
63245986
102334155

问题是System.in.read()。这读取 byte。例如,如果您输入 8,字符 '8' 将转换为 int56 并且您的程序将计算 56 个斐波那契数(非常慢,因为您不使用记忆)。

尝试

FibonacciPrint(new Scanner(System.in).nextInt());

相反。