2015-10-05 50 views
-2

我很困惑我爲什麼會遇到錯誤以及如何解決它。我的fibonacci序列版本應該只打印所需的目標索引值,並不是所有數字都像我見過的大多數其他斐波那契數列一樣。在Java斐波那契數列中編譯錯誤

import java.util.Scanner; 

public class Fibonacci_ronhoward 
{ 
public static void main(String[] args) 
{ 
    Scanner scan = new Scanner(System.in); 

    System.out.println("This is a Fibonacci sequence generator"); 

    System.out.println("Choose what you would like to do"); 

    System.out.println("1. Find the nth Fibonacci number"); 

    System.out.println("2. Find the smallest Fibonacci number that exceeds user given value"); 

    System.out.println("Enter your choice: "); 

    int choice = scan.nextInt(); 

    switch (choice) 
    { 
     case 1: 

      System.out.println(); 

      System.out.println("Enter the target index to generate (>1): "); 

      int n = scan.nextInt(); 

      int a = 0; 

      int b = 1; 

      for (int i = 1; i < n; i++) 
      { 

       int nextNumber = a + b; 
       a = b; 
       b = nextNumber; 

      } 

      System.out.println("The " + n + "th Fibonacci number is " + nextNumber + " "); 

      break; 

    } 


} 
} 
+1

不知道錯誤是什麼,您如何期待我們解決問題? –

回答

1

您在for循環定義nextNumber但隨後嘗試使用它以外的for循環範圍,這就是問題所在。

你應該在循環之外聲明它。

1

你的問題是在這裏:

for (int i = 1; i < n; i++) 
    { 
     //PROBLEM, nextNumber goes out of scope when loop exits 
     int nextNumber = a + b; 
     a = b; 
     b = nextNumber; 
    } 
    System.out.println("The " + n + "th Fibonacci number is " + nextNumber + " "); 

而是執行此操作:

int nextNumber = -1; 
    for (int i = 1; i < n; i++) 
    { 
     nextNumber = a + b; 
     a = b; 
     b = nextNumber; 
    } 
    System.out.println("The " + n + "th Fibonacci number is " + nextNumber + " "); 
+0

非常感謝!對於第二部分,我必須找到超出用戶給定值的最小斐波那契數,但在試圖找出如何接近它的方法時遇到困難,儘管我確信它與此相同。 – ronhoward

1

nextNumber在循環中定義的,因此超出範圍的的System.out.println()調用。