Java 数组倒计时循环的反转

Java 数组倒计时循环的反转,java,arrays,for-loop,reverse,Java,Arrays,For Loop,Reverse,我得到了错误 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("Count

我得到了错误

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?
    }
}
公共类反向{
公共静态void main(字符串[]args){
int i,j;
系统输出打印(“倒计时”\n);
int[]numIndex=new int[10];//包含10个元素的数组。
对于(i=0;i=0;j--){//可以使用i,这无关紧要。
System.out.println(numIndex[j]);//索引应该按与此处相反的顺序打印,但它会引发异常吗?
}
}

}

数组的大小为10,这意味着它可以从0到9进行索引
numIndex[10]
确实是出界了。这是一个基本的一对一错误。

Java使用基于0的数组索引。创建大小为10的数组时,它会在数组中创建10个整数“单元格”。索引为:0、1、2、…、8、9


循环计数到的索引小于11或10,并且该索引不存在。

java中具有
10
元素的
数组从
0
9
。所以你的循环需要覆盖这个范围。目前,您正在从
0
10
10
0
,您在
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?   
    } 

  }
}
公共类反向{
公共静态void main(字符串[]args){
int i,j;
系统输出打印(“倒计时”\n);
int[]numIndex=new int[10];//包含10个元素的数组。
对于(i=0;i=0;j--){//从9到0
System.out.println(numIndex[j]);//索引应该按与此处相反的顺序打印,但它会引发异常吗?
} 
}
}
记住,索引从0开始


这个数组有10个元素长。你从0迭代到10,也就是11!这会导致索引越界错误。你真的应该在将来使用numIndex.length来防止这些任意数字再次出现,先生,哈哈。谢谢你@greedybuddah-新人