我不断得到字符串索引,我不知道问题出在哪里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的']'
索引是否小于字符串的"[~"
索引。

桃花长相依
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);
添加回答
举报
0/150
提交
取消