這是代碼:public class Test { public static void main(String[] args) { int[] a= new int[3]; System.out.print(a[a.length]); }}為什么這會在運行時導致 ArrayIndexOutOfBoundsExceptionwill ?
3 回答

米琪卡哇伊
TA貢獻1998條經驗 獲得超6個贊
它從 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]);
}
}

炎炎設計
TA貢獻1808條經驗 獲得超4個贊
你應該使用它:
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/150
提交
取消