方法一;递归(可以达到逐个输出的目的)
public class FibonacciTest { public long fibonacci(long number){ if (number==0||number==1){ return number; }else{ // 该方法里调该方法 return fibonacci(number-1)+fibonacci(number-2); } } public static void main(String[] args) { Scanner scanner=new Scanner(System.in); System.out.print("请输入打印的项数:"); Integer integer=scanner.nextInt(); FibonacciTest fibonacciTest=new FibonacciTest(); for (int i = 0; i < integer; i++) { System.out.print(fibonacciTest.fibonacci(i)+"\t"); } } }
方法二:数组 (也可以达到逐个输出的目的)
/**----------------------- 方法二: 数组 --------------------------*/ public static void main(String[] args) { Scanner scanner=new Scanner(System.in); System.out.println("请输入项数:"); Integer integer=scanner.nextInt(); int[]arr=new int[integer]; switch (integer){ case 1: arr[0]=0; System.out.println(arr[0]); break; case 2: arr[0]=0; arr[1]=1; System.out.println(arr[0]+"\t"+arr[1]+"\t"); break; default: arr[0]=0; arr[1]=1; for (int i = 2; i < integer; i++) { arr[i]=arr[i-1]+arr[i-2]; } for (int i = 0; i < arr.length; i++) { System.out.print(arr[i]+"\t"); } } }
方法三:for循环(这个方法只能两个两个的输出)
public static void main(String[] args) { int a = 0; int b = 1; for (int i = 0; i <= 3; i++) { System.out.print(a + "\t" + b + "\t"); a = a + b; b = a + b; } }