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é)構見上述兩張圖片
二、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]); } } }
到此這篇關于Java中ArrayIndexOutOfBoundsException 異常報錯的解決方案的文章就介紹到這了,更多相關Java ArrayIndexOutOfBoundsException 內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
SpringBoot響應處理之以Json數(shù)據(jù)返回的實現(xiàn)方法
這篇文章主要介紹了SpringBoot整合Web開發(fā)其中Json數(shù)據(jù)返回的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-09-09java開發(fā)CPU流水線與指令亂序執(zhí)行詳解
這篇文章主要為大家介紹了java開發(fā)CPU流水線與指令亂序執(zhí)行詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-09-09