数组倒序循环倒计时

8

我遇到了一个错误..


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

}


2
数组长度为10个元素。你应该从0到9进行迭代,这样就不会出现索引越界错误了。未来最好使用numIndex.length来避免这种任意的数字。 - greedybuddha
1
啊,对了先生,哈哈。谢谢@贪婪佛陀 - 新人。 - KamikazeStyle
4个回答

23

您声明了一个包含 10个元素 的整数数组。并且您正在从 i=0到i=10i=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?   
    } 

  }
}

请记住索引从0开始。

.


4

Java使用从0开始的数组索引。当你创建一个大小为10的整型数组new int[10],它会在数组中创建10个整数'单元格'。索引分别是:0,1,2,...,8,9。

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


1
这个数组大小是10,也就是说索引从0到9。numIndex[10] 超出了边界。这是一种基本的“差一”的错误。

1
在Java中,一个有10个元素的数组从0到9。因此,您的循环需要覆盖此范围。目前您正在从0到10和10到0进行循环。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接