java 在这种情况下如何避免 ArrayIndexOutOfBoundsException?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17722959/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can i avoid ArrayIndexOutOfBoundsException in this case?
提问by ssindelar
Is it possible to avoid ArrayIndexOutOfBoundsException in this case ??
在这种情况下是否可以避免 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");
}
}
}
回答by ssindelar
Maybe I don't understand the real problem, but what prevents you to check if the index is inside the array before accessing it in this case?
也许我不明白真正的问题,但是在这种情况下,是什么阻止您在访问数组之前检查索引是否在数组内?
if (myIndex < myFirstStringArray.length) {
System.out.println("Present");
} else {
System.out.println("Not Present");
}
回答by user2277872
In arrays, they are measured differently than numbers. The first object inside an array is considered 0. So, in your if statement, instead of a 3, you just put a 2.
在数组中,它们的测量方式与数字不同。数组中的第一个对象被视为 0。因此,在 if 语句中,您只需输入 2,而不是 3。
if (myFirstStringArray[3] != null) {
System.out.println("Present");
to
到
if (myFirstStringArray[2] != null) {
System.out.println("Present");
Hope this helps! :)
希望这可以帮助!:)
回答by Sachin Verma
Your String
array contains 3 elements and you are accessing array[3] i.e. 4th element as index in 0 based and so you get this error (Exception, anyway).
您的String
数组包含 3 个元素,并且您正在访问数组 [3],即第 4 个元素作为基于 0 的索引,因此您会收到此错误(无论如何都是异常)。
To avoid the ArrayIndexOutOfBoundsException
use an index within specified index range. And always check whether your index is >=
array.length
.
避免ArrayIndexOutOfBoundsException
使用指定索引范围内的索引。并始终检查您的索引是否为>=
array.length
.