英文:
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>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论