在这种情况下是否可以避免ArrayIndexOutOfBoundsException?
package com;
public class Hi {
public static void main(String args[]) {
String[] myFirstStringArray = new String[] { "String 1", "String 2",
"String 3" };
if (myFirstStringArray[3] != null) {
System.out.println("Present");
} else {
System.out.println("Not Present");
}
}
}
答案 0 :(得分:5)
也许我不明白真正的问题,但是在这种情况下,在访问它之前是什么阻止你检查索引是否在数组内?
if (myIndex < myFirstStringArray.length) {
System.out.println("Present");
} else {
System.out.println("Not Present");
}
答案 1 :(得分:2)
在数组中,它们的测量方式与数字不同。数组中的第一个对象被认为是0.因此,在if语句中,而不是3,你只需要一个2。
if (myFirstStringArray[3] != null) {
System.out.println("Present");
到
if (myFirstStringArray[2] != null) {
System.out.println("Present");
希望这有帮助! :)
答案 2 :(得分:0)
你的String
数组包含3个元素,你正在访问数组[3],即第4个元素作为基于0的索引,所以你得到这个错误(无论如何)。
避免ArrayIndexOutOfBoundsException
使用指定索引范围内的索引。并始终检查您的索引是>=
array.length
。