获得句子中Java的平均长度

时间:2015-02-06 17:00:11

标签: java

我的代码似乎差不多正确。我得到的答案是3.0但它应该是2.6。我已经谷歌搜索/查看其他stackoverflow答案,但我没有修复。一直试图做这个错误2个小时。

代码:

public class Sentence { // words holds the array.
private static String[] words = {"hi","my","name","is","Bob"};
}

public String toString() { //Returns the array into Strings.
    return Arrays.toString(words);
}

    public double meanLength(String s) { 
    String wordysplit[] = toString().split(", ");
    float numWords = wordysplit.length;
    float totalChar = 0;
    for (int i = 0; i < numWords; i++) {
        totalChar += wordysplit[i].length();

    }
    return (totalChar / numWords);
}    

public static void main(String[] args) // Really simplified this code to make it
cleaner for you guys
System.out.println("Mean word length:"+words.meanLength());

       }
}

感谢所有帮助。谢谢。

1 个答案:

答案 0 :(得分:1)

这是一种更简单的方法

String resultString = StringUtils.join(words, "");
float avg = (float)resultString.length() / words.length;

请注意,StringUtils是来自Apache公地的一个类。

http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html

如果您不想将Apache commons添加到项目中,则可以使用此简单算法从数组中创建String

String[] array = {"AB", "B", "C"};
StringBuilder builder = new StringBuilder();
for(String s : array) {
    builder.append(s);
}

System.out.println((float)builder.toString().length() / array.length);

1.3333334打印为avg