为了账号安全,请及时绑定邮箱和手机立即绑定

有目的地避免 ArrayIndexOutOfBoundsException

有目的地避免 ArrayIndexOutOfBoundsException

长风秋雁 2023-03-23 16:52:02
string.split("\n")[1]总是给我一个ArrayIndexOutOfBoundsException。有没有办法防止这种情况发生?是否存在像下面这样的真实代码?if(!ArrayIndexOutOfBoundsException)     string.split("\n")[1]
查看完整描述

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.");

}


查看完整回答
反对 回复 2023-03-23
?
素胚勾勒不出你

TA贡献1827条经验 获得超9个赞

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



查看完整回答
反对 回复 2023-03-23
?
叮当猫咪

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


查看完整回答
反对 回复 2023-03-23
?
慕运维8079593

TA贡献1876条经验 获得超5个赞

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


try{

     string.split("\n")[1];

}catch(ArrayIndexOutOfBoundsException e){

      //here for example you can 

      //print an error message

}


查看完整回答
反对 回复 2023-03-23
  • 4 回答
  • 0 关注
  • 138 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号