天天看點

Exception in thread “main“ java.lang.ArrayIndexOutOfBoundsException: 6問題

今天在java中出現了一個這樣的問題

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6

at com.wyt.demo3.Role.attack(Role.java:126)

at com.wyt.demo3.RoleGameTest.main(RoleGameTest.java:24)

後來發現是“數組越界”的問題

例如:建立一個數組:int[] arr = {1,2,3,4,5,6};

數組内配置設定了6個空間,索引從0-5,

但你在方法中定義了索引 [6]。

例如:

Exception in thread “main“ java.lang.ArrayIndexOutOfBoundsException: 6問題

int[] arr = {1,2,3,4,5,6};

System.out.println(arr[6]);

因為不存在索引為6的空間,這樣就會出現上述問題。