亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么這會在運行時導致 ArrayIndexOutOfBoundsException?

為什么這會在運行時導致 ArrayIndexOutOfBoundsException?

慕桂英546537 2021-12-01 20:02:51
這是代碼:public class Test {    public static void main(String[] args) {        int[] a= new int[3];        System.out.print(a[a.length]);    }}為什么這會在運行時導致 ArrayIndexOutOfBoundsExceptionwill ?
查看完整描述

3 回答

?
白豬掌柜的

TA貢獻1893條經驗 獲得超10個贊

a.length 返回數組中元素的數量,這里是 3。

數組索引從 0 開始。有 3 個元素,它會變成 0,1,2。

沒有索引 3,因此例外。


查看完整回答
反對 回復 2021-12-01
?
米琪卡哇伊

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]);

       }

    }


查看完整回答
反對 回復 2021-12-01
?
炎炎設計

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]) 導致數組索引越界異常。


查看完整回答
反對 回復 2021-12-01
  • 3 回答
  • 0 關注
  • 234 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號