Java中ArrayIndexOutOfBoundsException 異常報錯的解決方案
一、ArrayIndexOutOfBoundsException異常報錯原因分析
ArrayIndexOutOfBoundsException 數(shù)組下標越界異常
異常報錯信息案例:
案例1:

案例2:

異常錯誤描述:
錯誤原因:數(shù)組下標越界異常;超出了數(shù)組下標的取值范圍,數(shù)組下標的取值范圍是 [0,arr.length-1],即 0 ~ 數(shù)組的長度-1,而上述的兩個錯誤都是我們在訪問數(shù)組元素時,超出了數(shù)組下標的取值返回。
ArrayDemo
案例1:
public class ArrayDemo {
public static void main(String[] args) {
int[] arr = new int[5];
arr[5] = 100;
}
}ArrayDemo
案例2:
public class ArrayDemo {
public static void main(String[] args) {
int[] arr = new int[5];
for (int i = 0; i <= arr.length; i++) {
System.out.println(arr[i]);
}
}
}上述為錯誤代碼,項目結(jié)構(gòu)見上述兩張圖片
二、ArrayIndexOutOfBoundsException解決方案
解決思路:這里,我們只需要檢查我們在訪問的數(shù)組元素,何時出現(xiàn)了數(shù)組下標超出了其取值范圍并改正即可
案例1:

public class ArrayDemo {
public static void main(String[] args) {
int[] arr = new int[5];
arr[4] = 100;
}
}案例2:
第一種方式:

public class ArrayDemo {
public static void main(String[] args) {
int[] arr = new int[5];
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
}第二種方式:

public class ArrayDemo {
public static void main(String[] args) {
int[] arr = new int[5];
for (int i = 0; i <= arr.length-1; i++) {
System.out.println(arr[i]);
}
}
}到此這篇關(guān)于Java中ArrayIndexOutOfBoundsException 異常報錯的解決方案的文章就介紹到這了,更多相關(guān)Java ArrayIndexOutOfBoundsException 內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用JSONObject.toJSONString 過濾掉值為空的key
這篇文章主要介紹了使用JSONObject.toJSONString 過濾掉值為空的key,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-03-03
在java中實現(xiàn)C#語法里的按引用傳遞參數(shù)的方法
下面小編就為大家?guī)硪黄趈ava中實現(xiàn)C#語法里的按引用傳遞參數(shù)的方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-09-09
java多線程批量拆分List導入數(shù)據(jù)庫的實現(xiàn)過程
這篇文章主要給大家介紹了關(guān)于java多線程批量拆分List導入數(shù)據(jù)庫的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2021-10-10

