【发布时间】:2013-06-01 21:41:37
【问题描述】:
我得到了错误..
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 个元素。您从 0 迭代到 10,即 11!这会导致索引越界错误。您将来真的应该使用 numIndex.length 来防止这些任意数字
-
啊,对了,先生,哈哈。谢谢@greedybuddah - 新人
标签: java arrays for-loop reverse