我收到错误..
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 个元素
的整数上声明了数组。您正在从 i=0 到 i=10
和 i=10 到 i=0
迭代,这是 11 个元素
。显然这是一个索引越界错误
。
将你的代码改成这样
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?
}
}
}
Remember indices starts from 0.
.
关于java - 数组倒计时的反向循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16952645/