如何在Java程序中解决“令牌=“ =”上的语法错误[关闭]

问题描述 投票:-1回答:2

我收到编译阶段错误消息,但我不知道如何修复代码。

我的代码如下:

public class Fibonacci {

    public static void main(String[] args) {
        int[] n = new int[] { 25 };
        int a = 1;
        int b = 1;

        for(int i = 0; i < n.length; i++) {
            while(n[i] > 2) {
                int tmp = b;
                b = a + b;
                a = tmp;
                n = [n - 1];
                System.out.println(b + " ");
            }
        }
    }
}
java arrays syntax-error expression fibonacci
2个回答
0
投票

n是一个数组,不能使用n = [n-1];在上面。如果要减少存储在n [i]中的值,则必须使用n [i] = n [i] -1;完整的代码将是

public class Some {
    public static void main(String[] args) {
        int[] n = new int[]{25};
        int a = 1;
        int b = 1;

        for (int i = 0; i < n.length; i++) {
            while (n[i] > 2) {
                int tmp = b;
                b = a + b;
                a = tmp;
                n[i] = n[i]-1;
                System.out.println(b + " ");
            }
        }
    }
}

但是我仍然不太了解您的代码打算做什么...


0
投票

您可以打印斐波那契序列,例如使用以下代码:

public class Fibonacci {
    public static void main(String[] args) {

        int current = 1;
        int previous = 0;
        int temp = 0;

        System.out.print("fibonacci sequence: " + previous + ", " + current + ", ");
        for (int i = 2; i<=25; i++) {
            temp = current;
            current = current + previous;
            previous = temp;

            System.out.print(current + ", ");
        }
    }
}

© www.soinside.com 2019 - 2024. All rights reserved.