是什么 ArrayIndexOutOfBoundsException 我的意思是我该怎么摆脱它?下面是触发异常的代码示例:
ArrayIndexOutOfBoundsException
String[] names = { "tom", "bob", "harry" }; for (int i = 0; i <= names.length; i++) { System.out.println(names[i]); }
thtygnil16#
来自这篇优秀的文章:for循环中的arrayindexoutofboundsexception简而言之:在的最后一次迭代中
for (int i = 0; i <= name.length; i++) { ``` `i` 将等于 `name.length` 这是非法索引,因为数组索引是基于零的。 你的代码应该是
for (int i = 0; i < name.length; i++)^
drkbr07n17#
if (index < 0 || index >= array.length) { // Don't use this index. This is out of bounds (borders, limits, whatever). } else { // Yes, you can safely use this index. The index is present in the array. Object element = array[index]; }
java教程-语言基础-数组更新:根据你的代码片段,
for (int i = 0; i<=name.length; i++) {
索引包含数组长度。这是不允许的。你需要替换 <= 由 < .
<=
<
for (int i = 0; i < name.length; i++) {
17条答案
按热度按时间thtygnil16#
来自这篇优秀的文章:for循环中的arrayindexoutofboundsexception
简而言之:
在的最后一次迭代中
for (int i = 0; i < name.length; i++)
^
drkbr07n17#
另请参见:
java教程-语言基础-数组
更新:根据你的代码片段,
索引包含数组长度。这是不允许的。你需要替换
<=
由<
.