字符串集的平均字长

时间:2017-08-31 02:19:15

标签: java string

我正在尝试获取一组字符串的平均字长,而且我遇到了以下错误:

  

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;
}

1 个答案:

答案 0 :(得分: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;
    }
}
相关问题