【问题标题】:reverse for loop for array countdown数组倒计时的反向循环
【发布时间】:2013-06-01 21:41:37
【问题描述】:

我得到了错误..

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 个元素。您从 0 迭代到 10,即 11!这会导致索引越界错误。您将来真的应该使用 numIndex.length 来防止这些任意数字
  • 啊,对了,先生,哈哈。谢谢@greedybuddah - 新人

标签: java arrays for-loop reverse


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      具有10 元素的Java 中的Array0 变为9。所以你的循环需要覆盖这个范围。目前你从010,和100

      【讨论】:

        【解决方案4】:

        您在 10 elements 的整数上声明了数组。您正在从i=0 to i=10i=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 开始。

        【讨论】:

          猜你喜欢
          • 2016-11-06
          • 1970-01-01
          • 2021-10-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多