用于阵列倒计时的循环反向

Kam*_*yle 6 java arrays reverse for-loop

我收到错误..

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
    at Reverse.main(Reverse.java:20). 
Run Code Online (Sandbox Code Playgroud)

语法没有错,所以我不确定为什么编译时会出错?

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?
    }
}
Run Code Online (Sandbox Code Playgroud)

}

abh*_*jia 19

你在整数上声明了数组10 elements.你正在迭代i=0 to i=10,i=10 to i=0那就是11 elements.显然这是一个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?   
    } 

  }
}
Run Code Online (Sandbox Code Playgroud)

记住索引从0开始.

.


rol*_*lfl 4

Java 使用从 0 开始的数组索引。当您创建大小为 10 的数组时,new int[10]它会在数组中创建 10 个整数“单元”。索引为:0、1、2、...、8、9。

您的循环计数到比 11 少 1 的索引,即 10,并且该索引不存在。