2017-08-31 6 views
2

私は、文字列の集合の平均ワード長を取得しようとしていますし、私は以下のエラーに実行しています:範囲外の文字列インデックス:平均ワード長

java.lang.StringIndexOutOfBoundsException :-1

私は原因がわかりません。

static double getAverageWordLength() { 

    // TODO: update the code here to return the average length of words in the tweets processed so far. 

    String[] average = tweeps.split(" "); 

    int count = 0; 
    int sum = 0; 
    int currentWordLength; 
    String tempString; 
    for(int i = 0; i < average.length; i++) 
    { 
     average[i] = average[i].replaceAll("[^a-zA-Z]", "").toLowerCase(); 
     tempString = average[i]; 
     currentWordLength = tempString.length(); 
     sum += currentWordLength; 
     count++; 
    } 
    double averageWordLength = sum/count; 
    return averageWordLength; 
} 
+0

コードの行は、例外から来るん:ここに私のコードはありますか? – 4castle

+4

私の環境では再生できません。 'tweeps'の価値は何ですか? – ymonad

+0

ちなみに、 'sum/count'は整数除算をしています(小数点以下の数字は切り捨てます)。操作を実行する前に 'double * 'に計算を進めるために、おそらく' 1.0 * sum/count'が必要です。 – 4castle

答えて

2
import java.lang.*; 

class test{ 

    public static void main(String args[]) 
    { 
     String MySentence = "This is My Word. I'm Going to Find the Average of this"; 
     System.out.println(" Average Length :"+ getAverageWordLength(MySentence)); 
    } 

    static double getAverageWordLength(String tweeps) { 

     // TODO: update the code here to return the average length of 
     // words in the tweets processed so far. 

     String[] average = tweeps.split(" "); 

     int count = 0; 
     int sum = 0; 
     int currentWordLength; 
     String tempString; 
     for(int i = 0; i < average.length; i++) 
     { 
      average[i] = average[i].replaceAll("[^a-zA-Z]", "").toLowerCase(); 
      tempString = average[i]; 
      currentWordLength = tempString.length(); 
      sum += currentWordLength; 
      count++; 
     } 
     double averageWordLength = sum/count; 
     return averageWordLength; 
    } 
} 
+0

何を変更しましたか? – Jack

+0

以下のgetAverageWordLength(MySentence)のようにmain関数のパラメータとして "tweeps"を渡します。 "tweeps"は実行時に値を持ちます。 –

+0

クラス内に静的なプライベート文字列としてtweepsがあり、そのクラス内に関数があります。あなたと同じことをしないだろうか?それが問題なのかどうかはわかりません。 – Jack