有目的地避免ArrayIndexOutOfBoundsException

时间:2019-07-13 20:16:18

标签: java arrays string

string.split("\n")[1]总是给我ArrayIndexOutOfBoundsException。有办法防止这种情况吗?是否存在类似以下的真实代码?

if(!ArrayIndexOutOfBoundsException)
    string.split("\n")[1]

4 个答案:

答案 0 :(得分:1)

string.split("\n")返回一个String数组。
string.split("\n")[1]假定返回值是一个至少包含两个元素的数组。
ArrayIndexOutOfBoundsException表示该数组具有少于两个元素

如果要防止发生该异常,则需要检查数组的长度。像...

String[] parts = string.split("\n");
if (parts.length > 1) {
    System.out.println(parts[1]);
}
else {
    System.out.println("Less than 2 elements.");
}

答案 1 :(得分:1)

数组的第一个元素位于索引0。不要假设总是有两个元素。数组中的最后一个索引的索引为(length-1)。

答案 2 :(得分:0)

索引从0开始,因此通过从1开始索引,您试图获取数组的第二个元素,在您的情况下,这是文本的第二行。您遇到这种错误是因为您的字符串中可能没有换行符,为避免此类异常,您可以使用try catch块(我不喜欢这种方法),也可以只检查是否有换行符您的字符串,您可以这样做:

if(yourString.contains("\n")){
    //split your string and do the work
}

或什至通过检查因分割而造成的零件长度:

String[] parts = yourString.split("\n");
if(parts.length>=2){
    //do the work
}

如果要使用try-catch块:

try {
    String thisPart = yourString.split("\n")[1];
}
catch(ArrayIndexOutOfBoundsException e) {
    //  Handle the ArrayIndexOutOfBoundsException case
}
//  continue your work

答案 3 :(得分:-1)

您可以轻松地使用 try-catch 避免收到此消息:

try{
     string.split("\n")[1];
}catch(ArrayIndexOutOfBoundsException e){
      //here for example you can 
      //print an error message
}