Java Recursive Method (Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4)

huangapple go评论64阅读模式
英文:

Java Recursive Method (Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4)

问题

    public static void main(String[] args) {
        int v = 1;
        int x = 2;
        String y = "dog";
        String z = "cat";
        Object[] a = {v, x, y, z};
        printReverse(a, a.length);
    }
    public static void printReverse(Object[] arr, int i) {
        if (i > 0) {
            System.out.println(arr[i]);
            printReverse(arr, i - 1);
        }
        else {
            return;
        }
    }
}
英文:

I'm trying to take an object array and print out the reverse using a recursive method but I'm getting the above listed error. Could someone help me out?

    public static void main(String[] args) {
        int v = 1;
        int x = 2;
        String y = "dog";
        String z = "cat";
        Object[] a = {v, x, y, z};
        printReverse(a, a.length);
    }
    public static void printReverse(Object[] arr, int i) {
        if (i > 0) {
            System.out.println(arr[i]);
            printReverse(arr, i - 1);
        }
        else {
            return;
        }
    }
}

</details>


# 答案1
**得分**: 1

你对`printReverse`的初始调用需要传递`a.length - 1`。由于数组是从0开始索引的,你在初始调用时就已经越界,还没有进行递归调用。

<details>
<summary>英文:</summary>

Your initial call to `printReverse` needs to pass `a.length -1`. You’re going out of bounds on the initial call before it ever recurses since arrays are 0-indexed

</details>



# 答案2
**得分**: 0

错误信息表示您正在访问数组元素4,但只有索引为0到3的元素。在Java中,数组索引从0开始。

<details>
<summary>英文:</summary>

The error message means you are accessing array element 4 but there are only elements with index 0 to 3. Array indices in Java start at 0.

</details>



huangapple
  • 本文由 发表于 2020年10月12日 10:40:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/64311014.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定