[英]How come I can't count downwards on an array in Java?
I am currently trying to take the elements of an array and reverse its order in Java. 我目前正在尝试采用数组的元素并在Java中颠倒其顺序。 How come I cannot print the elements of the array by counting downwards using a for loop without changing the actual ordering of elements in my array?
在不更改数组中元素的实际顺序的情况下,为什么不能通过使用for循环向下计数来打印数组的元素?
private void printArray(int[] array) {
for (int i = array.length; i >= 0; i--){
println(array[i]);
}
}
Array indices start at 0
and end at array.length - 1
. 数组索引从
0
开始,到array.length - 1
结束。 Here, you get an ArrayIndexOutOfBOundsException
since your first read is past the end of the array ( int i = array.length;
). 在这里,您将获得
ArrayIndexOutOfBOundsException
因为您的第一次读取超出了数组的末尾( int i = array.length;
)。
Do: 做:
for (int i = array.length - 1; i >= 0; i--)
println(array[i]);
Try 尝试
for (int i = array.length - 1; -1 != i; --i){
As indexes start from 0 索引从0开始
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.