# Java 程序：使用循环显示 Fibonacci 序列

> 原文： [https://beginnersbook.com/2017/09/java-program-to-display-fibonacci-series-using-loops/](https://beginnersbook.com/2017/09/java-program-to-display-fibonacci-series-using-loops/)

Fibonacci 序列是一序列数字，其中数字是前两个数字的总和。从 0 和 1 开始，序列变为`0,1,1,2,3,5,8,13,21`等。在这里，我们将编写三个程序来打印斐波纳契序列 1）使用`for`循环 2）使用`while`循环 3）基于用户输入的数字

要理解这些程序，你应该拥有[`for`循环](https://beginnersbook.com/2015/03/for-loop-in-java-with-example/) 和[`while`循环](https://beginnersbook.com/2015/03/while-loop-in-java-with-examples/)的知识。

> 如果您是 java 新手，请参考 [java 编程教程](https://beginnersbook.com/java-tutorial-for-beginners-with-examples/)开始学习基础知识。

## 示例 1：使用`for`循环打印斐波纳契序列

```java
public class JavaExample {

    public static void main(String[] args) {

        int count = 7, num1 = 0, num2 = 1;
        System.out.print("Fibonacci Series of "+count+" numbers:");

        for (int i = 1; i <= count; ++i)
        {
            System.out.print(num1+" ");

            /* On each iteration, we are assigning second number
             * to the first number and assigning the sum of last two
             * numbers to the second number
             */
            int sumOfPrevTwo = num1 + num2;
            num1 = num2;
            num2 = sumOfPrevTwo;
        }
    }
}
```

输出：

```java
Fibonacci Series of 7 numbers:0 1 1 2 3 5 8
```

## 示例 2：使用`while`循环显示 Fibonacci 序列

```java
public class JavaExample {

    public static void main(String[] args) {

        int count = 7, num1 = 0, num2 = 1;
        System.out.print("Fibonacci Series of "+count+" numbers:");

        int i=1;
        while(i<=count)
        {
            System.out.print(num1+" ");
            int sumOfPrevTwo = num1 + num2;
            num1 = num2;
            num2 = sumOfPrevTwo;
            i++;
        }
    }
}
```

输出：

```java
Fibonacci Series of 7 numbers:0 1 1 2 3 5 8
```

## 示例 3：基于用户输入显示斐波那契序列

该程序根据用户输入的数字显示顺序。例如 - 如果用户输入 10，则此程序显示 10 个数字的序列。

```java
import java.util.Scanner;
public class JavaExample {

    public static void main(String[] args) {

        int count, num1 = 0, num2 = 1;
        System.out.println("How may numbers you want in the sequence:");
        Scanner scanner = new Scanner(System.in);
        count = scanner.nextInt();
        scanner.close();
        System.out.print("Fibonacci Series of "+count+" numbers:");

        int i=1;
        while(i<=count)
        {
            System.out.print(num1+" ");
            int sumOfPrevTwo = num1 + num2;
            num1 = num2;
            num2 = sumOfPrevTwo;
            i++;
        }
    }
}
```

输出：

```java
How may numbers you want in the sequence:
6
Fibonacci Series of 6 numbers:0 1 1 2 3 5
```

查看这些相关的 Java 程序：

1.  [Java 程序：寻找因子](https://beginnersbook.com/2017/09/java-program-to-find-factorial-using-for-and-while-loop/)
2.  [Java 程序：检查素数](https://beginnersbook.com/2014/01/java-program-to-check-prime-number/)