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

我不断得到字符串索引,我不知道问题出在哪里

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();
    }}


慕村225694
浏览 1434回答 3
3回答

ibeautiful

字符串索引超出范围:-30异常表示您曾经substring()在字符串中返回一个子字符串,长度为29个字符长,第二个参数substring()为负数。所以你的字符串不包含char ']'。你必须做的是while像这样扩展条件:while (commentBody.contains("[~") && commentBody.contains("]")) {     ...........}另外,为了覆盖']'字符串中存在但位置在之前的其他情况"[~",您需要在获得子字符串之前检查char的']'索引是否小于字符串的"[~"索引。

桃花长相依

检查您的commentBody.indexOf("[~")+2索引是否等于或大于字符串的长度。int startIndex = commentBody.indexOf("[~")+2;int endIndex = commentBody.indexOf("]");if(startIndex <= commentBody.length() && startIndex <= endIndex)&nbsp; &nbsp;username = commentBody.substring(startIndex, endIndex);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java