是什么导致java.lang.arrayindexoutofboundsexception以及如何防止它?

ehxuflar  于 2021-06-30  发布在  Java
关注(0)|答案(17)|浏览(369)

是什么 ArrayIndexOutOfBoundsException 我的意思是我该怎么摆脱它?
下面是触发异常的代码示例:

String[] names = { "tom", "bob", "harry" };
for (int i = 0; i <= names.length; i++) {
    System.out.println(names[i]);
}
yxyvkwin

yxyvkwin16#

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` 尝试访问不存在的name.length索引元素(数组索引以长度-1结尾)时发生。只要将<=替换为<=就可以解决这个问题。

for(int i = 0; i < name.length; i++) {
System.out.print(name[i] +'\n'); // i goes from 0 to length - 1, Correct
}

tcomlyy6

tcomlyy617#

对于给定的数组,数组的长度是3(即name.length=3)。但当它存储从索引0开始的元素时,它的最大索引为2。
因此,您应该编写“i<name.length”而不是“i<=name.length”,以避免“arrayindexoutofboundsexception”。

相关问题