有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

数组需要帮助解决Java中的ArrayIndexOutOfBounds异常

我正在尝试运行一个调用下面的类方法的方法。每次我调用computeIterative()方法时,都会得到ArrayIndexOutOfBoundsException。我添加了一些代码来打印出循环,我看到异常在循环的第二次出现,但是循环会一直持续到完成。我做错了什么,无法解决此数组异常

static int computeIterative(int n) {

    efficiency = 0;
    int[] a = new int[n];
    int firstInt = 0;
    int secondInt = 1;
    int results = 0;
    if (n > 1) {
        a[0] = 0;
        a[1] = 1;

        for (int i = 2; i <= n; ++i) {
            efficiency++;
            firstInt = a[i-1];
            secondInt = a[i-2];
            results = 2 * firstInt + secondInt;
            System.out.println("Loop " + efficiency + " of " + n );
            System.out.println(firstInt);
            System.out.println(secondInt);
            System.out.println("Results: " + results);
            a[i] = results;
        }
    } else {
        a[0] = 0;
        a[1] = 1;
    }

    return a[n];

}

谢谢你的帮助


共 (3) 个答案

  1. # 1 楼答案

    错误在于线路

    a[i] = results;
    

    在for循环中,您一直在使用:

    for(i=2;i<=n;i++)
    

    您会发现数组索引从0开始,一直到n-1。因此,当您使用:

    i <= n
    

    您将遇到数组越界异常,因为它没有第n个元素

    将for循环条件更改为:

    i <= n 
    

    致:

    i < n
    

    你的代码应该可以工作

  2. # 2 楼答案

    您已启动大小为“n”的数组,您正在尝试访问[n]元素,数组索引从0开始到n-1。因此,当您访问[n]时,您将获得Arrayindexboundexception。 将此行从

    int[] a = new int[n];int[] a = new int[n+1];(第3行)

    工作

  3. # 3 楼答案

    如果n为2,则访问[2](a[i]=results;)但是只有元素0和1