ArrayIndexOutOfBoundsException是什么意思,我如何摆脱它?
下面是一个触发异常的代码示例:
String[] names = { "tom", "bob", "harry" };
for (int i = 0; i <= names.length; i++) {
System.out.println(names[i]);
}
ArrayIndexOutOfBoundsException是什么意思,我如何摆脱它?
下面是一个触发异常的代码示例:
String[] names = { "tom", "bob", "harry" };
for (int i = 0; i <= names.length; i++) {
System.out.println(names[i]);
}
当前回答
根据贵公司守则:
String[] name = {"tom", "dick", "harry"};
for(int i = 0; i<=name.length; i++) {
System.out.print(name[i] +'\n');
}
如果你检查 System.out.print (name.length);
你会得到3;
也就是说你的名字长度是3
你的循环从0运行到3 它应该是0到2或者1到3
回答
String[] name = {"tom", "dick", "harry"};
for(int i = 0; i<name.length; i++) {
System.out.print(name[i] +'\n');
}
其他回答
如果您使用数组的长度来控制for循环的迭代,请始终记住数组中第一项的索引为0。所以数组中最后一个元素的下标比数组的长度小1。
这意味着您正在尝试访问一个数组的索引,该索引是无效的,因为它不在边界之间。
例如,这将初始化一个上限为4的基元整数数组。
int intArray[] = new int[5];
程序员从零开始计数。例如,这个会抛出一个ArrayIndexOutOfBoundsException,因为上限是4而不是5。
intArray[5];
你的第一个目标应该是能够合理清晰地解释它的文档:
抛出,表示使用非法索引访问了数组。索引值为负或大于或等于数组的大小。
例如:
int[] array = new int[5];
int boom = array[10]; // Throws the exception
至于如何避免……嗯,别这么做。小心你的数组索引。
人们有时会遇到的一个问题是认为数组是1索引的,例如。
int[] array = new int[5];
// ... populate the array here ...
for (int index = 1; index <= array.length; index++)
{
System.out.println(array[index]);
}
这将遗漏第一个元素(索引0),并在索引为5时抛出异常。这里的有效索引是0-4。正确的,地道的for语句应该是:
for (int index = 0; index < array.length; index++)
(当然,这是假设您需要索引。如果你可以使用增强的for循环,那就这样做。)
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++) {
由于i<=name,你会得到ArrayIndexOutOfBoundsException。长度的部分。的名字。Length返回字符串名称的长度,即3。因此,当您试图访问名称[3]时,它是非法的,并抛出异常。
解决代码:
String[] name = {"tom", "dick", "harry"};
for(int i = 0; i < name.length; i++) { //use < insteadof <=
System.out.print(name[i] +'\n');
}
它在Java语言规范中定义:
公共final字段长度,它包含组件的数量 数组的。长度可以为正或零。