编译Java Fibonacci序列中的错误

时间:2015-10-05 14:33:35

标签: java compilation sequence fibonacci

我很困惑为什么我会收到错误以及如何修复错误。我的斐波那契序列版本应该只打印所需的目标索引值,而不是像我之前看到的大多数其他斐波那契序列那样打印所有数字。

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;

    }


}
}

3 个答案:

答案 0 :(得分:1)

您在nextNumber循环中定义for但是然后尝试在for循环范围之外使用它,这就是问题所在。

你应该在循环之外声明它。

答案 1 :(得分: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 + " ");

答案 2 :(得分:1)

<input class="input" type="text">在循环中定义,因此超出了System.out.println()调用的范围。