Java中ArrayIndexOutOfBoundsException 異常報(bào)錯(cuò)的解決方案
一、ArrayIndexOutOfBoundsException異常報(bào)錯(cuò)原因分析
ArrayIndexOutOfBoundsException 數(shù)組下標(biāo)越界異常
異常報(bào)錯(cuò)信息案例:
案例1:
案例2:
異常錯(cuò)誤描述:
錯(cuò)誤原因:數(shù)組下標(biāo)越界異常;超出了數(shù)組下標(biāo)的取值范圍,數(shù)組下標(biāo)的取值范圍是 [0,arr.length-1],即 0 ~ 數(shù)組的長度-1,而上述的兩個(gè)錯(cuò)誤都是我們?cè)谠L問數(shù)組元素時(shí),超出了數(shù)組下標(biāo)的取值返回。
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]); } } }
上述為錯(cuò)誤代碼,項(xiàng)目結(jié)構(gòu)見上述兩張圖片
二、ArrayIndexOutOfBoundsException解決方案
解決思路:這里,我們只需要檢查我們?cè)谠L問的數(shù)組元素,何時(shí)出現(xiàn)了數(shù)組下標(biāo)超出了其取值范圍并改正即可
案例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 異常報(bào)錯(cuò)的解決方案的文章就介紹到這了,更多相關(guān)Java ArrayIndexOutOfBoundsException 內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot響應(yīng)處理之以Json數(shù)據(jù)返回的實(shí)現(xiàn)方法
這篇文章主要介紹了SpringBoot整合Web開發(fā)其中Json數(shù)據(jù)返回的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-09-09java開發(fā)CPU流水線與指令亂序執(zhí)行詳解
這篇文章主要為大家介紹了java開發(fā)CPU流水線與指令亂序執(zhí)行詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09編譯期動(dòng)態(tài)替換三方包中的Class文件過程詳解
這篇文章主要為大家介紹了編譯期動(dòng)態(tài)替換三方包中的Class文件過程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-03-03Java中StringBuilder常用構(gòu)造方法解析
這篇文章主要介紹了Java中StringBuilder常用構(gòu)造方法解析,StringBuilder是一個(gè)可標(biāo)的字符串類,我們可以吧它看成是一個(gè)容器這里的可變指的是StringBuilder對(duì)象中的內(nèi)容是可變的,需要的朋友可以參考下2024-01-01