1. 程式人生 > 其它 >Java異常理解之Exception in thread “main“ java.lang.ArrayIndexOutOfBoundsException

Java異常理解之Exception in thread “main“ java.lang.ArrayIndexOutOfBoundsException

這個異常是Java中的陣列越界問題

當你使用不合法的索引訪問陣列是會出現這種錯誤
例如:

 class Solution {
    public static int  climbStairs(int n) {
        if (n == 1 || n == 2) {
            return n;
        }
        int[] demo = new int[n];    
        demo[1]=1;
        demo[2]=2;
        for (int i = 3; i <=n; i++) {
            demo[i] 
= demo[i-1] + demo[i-2]; } return demo[n]; } } public class palouti { public static void main(String[] args) { System.out.println(Solution.climbStairs(3)); } }

發生這種錯誤的原因是:

在這個地方開闢陣列長度為n

int[] demo = new int[n];  

而在下面的使用中

for (int i = 3; i <=n; i++) {
            demo[i] 
= demo[i-1] + demo[i-2]; }

無論n的值為多少都會超出界限
因為陣列的索引是從 0 開始的,前面開闢的長度每次都差了一位
例如:n=3時,在 for 迴圈的索引中,都會索引到 demo[3],而從 0 開始索引,到demo[3]時,就相當於從 0-1-2-3,超出了陣列界限

解決方法也很簡單

只要將

int[] demo = new int[n];  

改為

int[] demo = new int[n+1];  

Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException:
這個異常會經常遇到,只要注意陣列的界限,就可以避免了