[英]reverse for loop for array countdown
我收到错误..
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
at Reverse.main(Reverse.java:20).
语法没有错,所以我不确定为什么编译时会出错?
public class Reverse {
public static void main(String [] args){
int i, j;
System.out.print("Countdown\n");
int[] numIndex = new int[10]; // array with 10 elements.
for (i = 0; i<11 ; i++) {
numIndex[i] = i;// element i = number of iterations (index 0=0, 1=1, ect.)
}
for (j=10; j>=0; j--){ // could have used i, doesn't matter.
System.out.println(numIndex[j]);//indexes should print in reverse order from here but it throws an exception?
}
}
}
您在10 elements
整数上声明了数组。 并且您从i=0 to i=10
迭代i=0 to i=10
并且i=10 to i=0
这是11 elements
。 显然这是一个index out of bounds error
的index out of bounds error
。
将您的代码更改为此
public class Reverse {
public static void main(String [] args){
int i, j;
System.out.print("Countdown\n");
int[] numIndex = new int[10]; // array with 10 elements.
for (i = 0; i<10 ; i++) { // from 0 to 9
numIndex[i] = i;// element i = number of iterations (index 0=0, 1=1, ect.)
}
for (j=9; j>=0; j--){ // from 9 to 0
System.out.println(numIndex[j]);//indexes should print in reverse order from here but it throws an exception?
}
}
}
记住索引从0开始。
。
Java使用基于0的数组索引。 当你创建一个大小为10的new int[10]
的数组时,它会在数组中创建10个整数'单元'。 索引是:0,1,2,....,8,9。
您的循环计数到索引,该索引小于11或10,并且该索引不存在。
该数组的大小为10,这意味着它可以从0到9进行numIndex[10]
确实超出了界限。 这是一个基本的逐个错误。
java中有10
元素的Array
从0
到9
。 所以你的循环需要覆盖这个范围。 目前你将从0
到10
,从10
到0
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.