Java中ArrayIndexOutOfBoundsException 異常報錯的解決方案
一、ArrayIndexOutOfBoundsException異常報錯原因分析
ArrayIndexOutOfBoundsException 數組下標越界異常
異常報錯信息案例:
案例1:
案例2:
異常錯誤描述:
錯誤原因:數組下標越界異常;超出了數組下標的取值范圍,數組下標的取值范圍是 [0,arr.length-1],即 0 ~ 數組的長度-1,而上述的兩個錯誤都是我們在訪問數組元素時,超出了數組下標的取值返回。
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]); } } }
上述為錯誤代碼,項目結構見上述兩張圖片
二、ArrayIndexOutOfBoundsException解決方案
解決思路:這里,我們只需要檢查我們在訪問的數組元素,何時出現了數組下標超出了其取值范圍并改正即可
案例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 內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
java開發(fā)CPU流水線與指令亂序執(zhí)行詳解
這篇文章主要為大家介紹了java開發(fā)CPU流水線與指令亂序執(zhí)行詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-09-09