4 回答

TA贡献1784条经验 获得超9个赞
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.");
}

TA贡献1776条经验 获得超12个赞
索引从 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

TA贡献1876条经验 获得超5个赞
您可以轻松地使用try-catch来避免收到此消息:
try{
string.split("\n")[1];
}catch(ArrayIndexOutOfBoundsException e){
//here for example you can
//print an error message
}
添加回答
举报