Java for(int:array)索引越界异常
我最近一直在学习Java,今天我遇到了一个我找不到有效解决方案的问题。 我的代码如下所示:Java for(int:array)索引越界异常,java,Java,我最近一直在学习Java,今天我遇到了一个我找不到有效解决方案的问题。 我的代码如下所示: public class testTable { public static void main(String[] args) { int bob[] = {456,2,3,4,5,6}; for(int j : bob) { System.out.println(bob[j]); } } } 代码始终返回错误: Exception in thre
public class testTable {
public static void main(String[] args) {
int bob[] = {456,2,3,4,5,6};
for(int j : bob) {
System.out.println(bob[j]);
}
}
}
代码始终返回错误:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 456
at com.Practice.thenewboston.Arrays.Table.testTable.main(testTable.java:9)
任何帮助都将不胜感激,对于错误发生的原因,最好能给出一个很好的解释。
谢谢 通过提供要从中获取值的位置的索引来引用数组。这些索引从零开始。因此,要从数组中获取第一个值,您需要执行
bob[0]
。for loop
所做的是自动遍历数组的每个元素,然后一个接一个地将值放入j
。所以要打印出值,只需执行System.out.println(j)
系统输出打印ln(j)代码>是您所使用的for循环(增强for循环)类型所需的内容
for(int j : bob) {
System.out.println(j);
}
或
for(int j=0;j
试试这个。。。
数组的第一个元素是456,而数组长度是6
,因此,您试图访问数组中不存在的索引。因此,它会导致IndexOutOfBoundException
你的循环应该是这样的
for(int j : bob) {
System.out.println(j);
}
这适用于集合通过提供要从中获取值的位置的索引来引用数组。这些索引从零开始。因此,要获得第一个值,您需要执行bob[0]
。for循环所做的是自动遍历数组的每个元素,然后一个接一个地将值放入j
。所以要打印出值,只需执行System.out.println(j)代码>哦,好的。非常感谢,这是我的课上没有提到的。我把我的评论作为答案。我希望这对你有所帮助:-)如果没有,在回答中添加一个新的注释。你可以把它看作是一个for-each,但它仍然是一个for循环。这被称为增强型for loop,因为他们提到他们正在学习Java,最好包含一个为什么提供这个答案。
public class testTable {
public static void main(String[] args) {
int bob[] = {456,2,3,4,5,6};
for(int j : bob) { //this is foreach not for loop be aware.
System.out.println(j);
}
}
}
for(int j : bob) {
System.out.println(j);
}