2015-10-05 31 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()调用。