Java 为什么这会导致运行时出现ArrayIndexOutOfBoundsException?
代码如下:Java 为什么这会导致运行时出现ArrayIndexOutOfBoundsException?,java,arrays,Java,Arrays,代码如下: public class Test { public static void main(String[] args) { int[] a= new int[3]; System.out.print(a[a.length]); } } 为什么这会导致运行时出现ArrayIndexOutofBoundsCeptionWill a.length返回数组中的元素数,这里是3 数组索引从0开始。如果有3个元素,则为0,1,2 没有索引3,因此有
public class Test {
public static void main(String[] args) {
int[] a= new int[3];
System.out.print(a[a.length]);
}
}
为什么这会导致运行时出现ArrayIndexOutofBoundsCeptionWill
a.length
返回数组中的元素数,这里是3
数组索引从0开始。如果有3个元素,则为0,1,2
没有索引3,因此有例外。索引从
0
开始(不是形式1
)。因此,在您的例子中,a
具有索引0
、1
和2
但您正在尝试访问索引3
(length
或size
)
使用
System.out.print(a[a.length]-1)代码>。您应该使用:
public class Test{
public static void main(String []args){
int[] a= new int[3];
System.out.print(a[a.length-1]);
}
}
说明:
a.length
将返回长度,即3(3个现有字段)。
但是a[3]
的索引从0开始,上升到2。
使用-1减少长度将返回最后一个真正存在的索引(2)
因此a[a.length]
(=a[3]
)会导致数组索引越界异常。它从0开始,因此必须更改为[a.length-1]
public class Test{
public static void main(String []args){
int[] a= new int[3];
System.out.print(a[a.length-1]);
}
}
这是IndexOutOfBoundsException
的层次结构:
java.lang.Object
java.lang.Throwable
java.lang.Exception
java.lang.RuntimeException
java.lang.IndexOutOfBoundsException
有时解决这个问题比较困难。在这些时刻,您可以使用空闲调试器。它将在图形界面中显示每次迭代时每个变量的值
您可以使用Eclipse
debugger、Netbeans
、visualstudio
code、Atom
扩展也可以使用。因为索引从0到2开始,而不是从1到3:)更改为System.out.print(a[a.length-1])
由于newint[3]的原因,它不应该编译代码>和publicclassTest
没有解释的代码通常无助于理解问题