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]);
}
当前回答
由于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字段长度,它包含组件的数量 数组的。长度可以为正或零。
其他回答
你的第一个目标应该是能够合理清晰地解释它的文档:
抛出,表示使用非法索引访问了数组。索引值为负或大于或等于数组的大小。
例如:
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循环,那就这样做。)
ArrayIndexOutOfBoundsException表示您正在尝试访问一个不存在或超出该数组界限的数组索引。数组索引从0开始,以长度- 1结束。
在你的情况下
for(int i = 0; i<=name.length; i++) {
System.out.print(name[i] +'\n'); // i goes from 0 to length, Not correct
}
当你试图访问时,ArrayIndexOutOfBoundsException会发生 这个名字。长度索引的元素不存在(数组索引以长度-1结束)。只需将<=替换为<就可以解决这个问题。
for(int i = 0; i < name.length; i++) {
System.out.print(name[i] +'\n'); // i goes from 0 to length - 1, Correct
}
ArrayIndexOutOfBoundsException名称本身解释了,如果您试图访问超出数组大小范围的索引值,则会发生此类异常。
在你的例子中,你可以从for循环中删除等号。
for(int i = 0; i<name.length; i++)
更好的选择是迭代数组:
for(String i : name )
System.out.println(i);
为了避免数组索引越界异常,应该在可以的地方和时候使用增强的for语句。
主要的动机(和用例)是当您迭代时,您不需要任何复杂的迭代步骤。您不能使用增强的for在数组中向后移动或只迭代每个其他元素。
在执行此操作时,您可以保证不会耗尽要迭代的元素,并且您的[修正]示例很容易转换。
代码如下:
String[] name = {"tom", "dick", "harry"};
for(int i = 0; i< name.length; i++) {
System.out.print(name[i] + "\n");
}
...等价于:
String[] name = {"tom", "dick", "harry"};
for(String firstName : name) {
System.out.println(firstName + "\n");
}
此错误发生在运行循环超过限制次数时。让我们考虑一个简单的例子,
class demo{
public static void main(String a[]){
int[] numberArray={4,8,2,3,89,5};
int i;
for(i=0;i<numberArray.length;i++){
System.out.print(numberArray[i+1]+" ");
}
}
首先,我将数组初始化为“numberArray”。然后,使用for循环打印一些数组元素。当循环运行'i'时,打印(numberArray[i+1]元素..(当i的值为1时,打印numberArray[i+1]元素)..假设当i=(numberArray.length-2)时,打印数组的最后一个元素,当i的值转到(numberArray.length-1)时,没有值可打印,此时会出现ArrayIndexOutOfBoundsException。我希望你能明白。谢谢你!