我不斷得到字符串索引,我不知道問題出在哪里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貢獻(xiàn)1993條經(jīng)驗 獲得超6個贊
字符串索引超出范圍:-30異常
表示您曾經(jīng)substring()
在字符串中返回一個子字符串,長度為29個字符長,第二個參數(shù)substring()
為負(fù)數(shù)。
所以你的字符串不包含char ']'
。
你必須做的是while
像這樣擴(kuò)展條件:
while (commentBody.contains("[~") && commentBody.contains("]")) { ...........}
另外,為了覆蓋']'
字符串中存在但位置在之前的其他情況"[~"
,您需要在獲得子字符串之前檢查char的']'
索引是否小于字符串的"[~"
索引。

桃花長相依
TA貢獻(xiàn)1860條經(jīng)驗 獲得超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
提交
取消