2016-10-30 4 views
0

ツイートにハッシュタグまたは言葉が含まれているかどうかを確認する基本コードを作成しています。次のスペースまたはタブがある場合はカウントされません。私はまた、 '閉じられていない文字のリテラル'メッセージを取得していると私はなぜか分からない。Error- 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

まず、コードを投稿するときに、tweetの文字列値が何であるか投稿してください。私たちは、文字列の長さは、あなたが第三の場所に0番目の位置から文字列のカウントを開始3.

であると仮定しましょう今の

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

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

:あなたのコード内

問題は、このです。 i+1を実行すると、存在しない文字列の4番目のインデックスにアクセスしようとしています。

また、あなたのループを変更する方法のない"/t"

可能な方法があるタブをチェックするために"\t"を使用します。このフォームでごfor-loopを作る

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 Wow Man !!!どのように私はこれを行うことができます...固定それを...!ありがとうございます –

0

for (int i=0; i < tweet.length()-1; i++) 
関連する問題