【问题标题】:foreach causing out of bounds error in Java when used with array [duplicate]与数组一起使用时,foreach 在 Java 中导致越界错误 [重复]
【发布时间】:2016-04-21 13:49:21
【问题描述】:

我想使用 foreach 循环打印数组中的所有元素

int[] array={1,2,3,4,5};
   for(int i:array)
       System.out.println(array[i]);

编译器给了我这个错误/警告

线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException: 5

但是当我打印别的东西时

int[] array={1,2,3,4,5};
   for(int i:array)
       System.out.println("Print something");

它写了五次“打印一些东西”并且没有给出警告/错误。

我认为它必须做一些事情,数组中的第一个元素的索引为 0,但我不确定。

谁能解释一下原因?

【问题讨论】:

  • 您确定这正是导致问题的代码吗?
  • @Jean-BaptisteYunès array[i] for each 循环是问题所在。
  • 哦,是的!我错过了重点!我太傻了……
  • i 迭代值而不是索引...

标签: java arrays foreach


【解决方案1】:

您正在迭代分配给i 的数组的内容,因此代码转换为

System.out.println(array[1]);
System.out.println(array[2]);
System.out.println(array[3]);
System.out.println(array[4]);
System.out.println(array[5]);   // ArrayIndexOutOfBoundsException

【讨论】:

    【解决方案2】:

    在您的第一段代码中,您没有打印数组中的所有元素。您正在遍历数组中的所有元素,并为每个元素打印数组中与该元素的值相对应的条目。

    你想要的是这个:

    int[] array={1,2,3,4,5};
       for(int i:array)
           System.out.println(i);
    

    【讨论】:

    • 谢谢,这正是我想要的。
    猜你喜欢
    • 2016-02-17
    • 1970-01-01
    • 2013-04-02
    • 1970-01-01
    • 1970-01-01
    • 2021-12-30
    • 1970-01-01
    • 1970-01-01
    • 2018-09-01
    相关资源
    最近更新 更多