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]);
}
当前回答
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
}
其他回答
数组中的每一项都称为一个元素,每个元素都通过它的数值索引来访问。如上图所示,编号从0开始。例如,第9个元素将因此在索引8处被访问。
抛出IndexOutOfBoundsException表示某种类型的索引(例如数组、字符串或向量)超出了范围。
任意数组X,可以从[0到(X.length - 1)]访问
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
}
对于多维数组,要确保访问正确维度的length属性可能有些棘手。以下面的代码为例:
int [][][] a = new int [2][3][4];
for(int i = 0; i < a.length; i++){
for(int j = 0; j < a[i].length; j++){
for(int k = 0; k < a[j].length; k++){
System.out.print(a[i][j][k]);
}
System.out.println();
}
System.out.println();
}
每个维度都有不同的长度,因此,中间循环和内部循环使用相同维度的length属性(因为a[i]。Length与a[j]. Length相同)。
相反,内部循环应该使用[i][j]。长度(或[0][0]。长度,为了简单)。
每当这个异常出现时,它意味着你正在尝试使用一个超出界限的数组索引,或者在外行术语中,你正在请求比你初始化的更多。
为了防止这种情况,总是要确保你没有请求一个数组中不存在的索引,即如果数组长度为10,那么你的索引必须在0到9之间
根据贵公司守则:
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');
}