数组倒计时的反向for循环

flseospp  于 2021-06-30  发布在  Java
关注(0)|答案(4)|浏览(375)

我得到了错误。。

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?
    }
}

}

pw9qyyiw

pw9qyyiw1#

您在的整数上声明了数组 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?   
    } 

  }
}

记住索引从0开始。
.

5ktev3wc

5ktev3wc2#

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

hpxqektj

hpxqektj3#

Array 在java中 10 元素来自 09 . 所以你的循环需要覆盖这个范围。现在你要从 010 ,和 100 .

ou6hu8tu

ou6hu8tu4#

java使用基于0的数组索引。创建大小为10的数组时 new int[10] 它在数组中创建10个整数“单元格”。索引为:0、1、2、…、8、9。
循环计数到1小于11或10的索引,并且该索引不存在。

相关问题