Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4 at com.wanglx.duotai.Practice_duotai.main(Practice_duotai.java:9)


Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4
at com.wanglx.duotai.Practice_duotai.main(Practice_duotai.java:9)

public class Practice_duotai {
    public static void main(String[] args) {
        Traffic [] t=new Traffic[4];
        t[1]=new Car();
        t[2]=new Bicycle();
        t[3]=new Car();
        t[4]=new Bicycle();
        for(int i=0;i<4;i++) {
            t[i].drive();
        }
        
    }
}
class Traffic{
    public void drive() {
        System.out.println("前進");
    }
}
class Car extends Traffic{
    public void  drive() {
        System.out.println("很快");
    }
}
class Bicycle extends Traffic{
    public void drive() {
        System.out.println("很慢");
    }
}

這是我學習“多態”時,練習的簡單代碼,當時運行的時候idea給出了

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4
    at com.wanglx.duotai.Practice_duotai.main(Practice_duotai.java:9)

這樣的錯誤代碼

這個異常是初學者比較常見的異常。
ArrayIndexOutOfBoundsException:注意這個單詞,字面意思就是數組引用超出界限,也就是我們常說的越界問題。
比如,我們創建了一個數組 int a[] = new int[4] ;
那么數組a只能存放四個元素,而數組的下標是從0開始的,也就是說,a[3]就是最后一個元素。當你給a[4]賦值,或者使用a[4]的時候,就出現了ArrayIndexOutOfBoundsException異常
修改以后
 1 package com.wanglx.duotai;
 2 
 3 public class Practice_duotai {
 4     public static void main(String[] args) {
 5         Traffic [] t=new Traffic[4];
 6        t[0]=new Car(); 7 t[1]=new Bicycle(); 8 t[2]=new Car(); 9 t[3]=new Bicycle(); //這里要注意 10         for(int i=0;i<4;i++) {
11             t[i].drive();
12         }
13         
14     }
15 }
16 class Traffic{
17     public void drive() {
18         System.out.println("前進");
19     }
20 }
21 class Car extends Traffic{
22     public void  drive() {
23         System.out.println("很快");
24     }
25 }
26 class Bicycle extends Traffic{
27     public void drive() {
28         System.out.println("很慢");
29     }
30 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM