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:
這個異常會經常遇到,只要注意數組的界限,就可以避免了


免責聲明!

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



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