2016-10-30 84 views
0

我正在編寫一個基本代碼,用於檢查tweet是否包含標籤或提及,如果其中任何一個有空格或標籤,則不會計數。我也收到了'未密封的字符'信息,我不知道爲什麼。錯誤 - StringIndexOutOfBoundsException:字符串索引超出範圍:4

for (int i=0; i < tweet.length(); i++) { 

     char currentchar = tweet.charAt(i); 
     char nextcar = tweet.charAt(i+1); 

     if (currentchar == '#') { 

     if (! (nextcar == ' ') && ! (nextcar == '/t')) { 

     numofhashtags++; 

     } 
     } 
     if (currentchar == '@') { 

     if ((nextcar != ' ') && (nextcar != '/t')) { 

     numofmentions++; 
     } 

     } 
    } 
+6

'我 Tom

+1

你明白錯誤信息是什麼意思嗎? –

回答

0

首先,當您發佈代碼時,請發佈推文的字符串值。

在你的代碼的問題是這樣的:

for (int i=0; i < tweet.length(); i++) { 

     char currentchar = tweet.charAt(i); 
     char nextcar = tweet.charAt(i+1);//<-- here 

現在讓我們假設該字符串的長度是3

你開始從第0個位置的字符串數到第三個位置。當你做i+1時,你試圖訪問不存在的字符串的第4個索引。

還可以使用"\t"檢查標籤不"/t"

,你可以如何改變你的循環可能的方式是:

for (int i=1; i <tweet.length(); i++) {//change i=1 and condition to <= 

     char currentchar = tweet.charAt(i-1);//since we are already accessing from the next character you will you have scan the previous character for current character by doing i-1 
     char nextcar = tweet.charAt(i);// you will already have next character access so no need of i+1 
+0

爲什麼要將第一行中的條件從'<'更改爲'<='? –

+0

@Tom那麼你是說這段代碼會失敗嗎? –

+1

@Tom哇哇!我該如何做到這一點...修正了它......!謝謝 –

0

以這種形式讓您for-loop

for (int i=0; i < tweet.length()-1; i++) 
相關問題