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

StringIndexOutOfBoundsException:字符串索引超出范围:

StringIndexOutOfBoundsException:字符串索引超出范围:

慕村225694 2019-04-20 18:19:06
我不断得到字符串索引,我不知道问题出在哪里String username, userDisplayName;while (commentBody.contains("[~")) {     username = commentBody.substring(commentBody.indexOf("[~")+2, commentBody.indexOf("]"));     try {         userDisplayName = connector.getUserByUsername(username).get().getDisplayName();         commentBody = commentBody.replace("[~" + username + "]", userDisplayName);     } catch (InterruptedException e) {         // TODO Auto-generated catch block         e.printStackTrace();     } catch (ExecutionException e) {         // TODO Auto-generated catch block         e.printStackTrace();     }}
查看完整描述

3 回答

?
ibeautiful

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

字符串索引超出范围:-30异常


表示您曾经substring()在字符串中返回一个子字符串,长度为29个字符长,第二个参数substring()为负数。
所以你的字符串不包含char ']'
你必须做的是while像这样扩展条件:

while (commentBody.contains("[~") && commentBody.contains("]")) {
    ...........}

另外,为了覆盖']'字符串中存在但位置在之前的其他情况"[~",您需要在获得子字符串之前检查char的']'索引是否小于字符串的"[~"索引。


查看完整回答
反对 回复 2019-05-15
?
桃花长相依

TA贡献1860条经验 获得超8个赞

检查您的commentBody.indexOf("[~")+2索引是否等于或大于字符串的长度。


int startIndex = commentBody.indexOf("[~")+2;

int endIndex = commentBody.indexOf("]");


if(startIndex <= commentBody.length() && startIndex <= endIndex)

   username = commentBody.substring(startIndex, endIndex);


查看完整回答
反对 回复 2019-05-15
  • 3 回答
  • 0 关注
  • 1433 浏览

添加回答

举报

0/150
提交
取消
微信客服

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

帮助反馈 APP下载

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

公众号

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