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]);
}
}
}
AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。
更多推荐


所有评论(0)