开发者社区 问答 正文

字符串数组中每个元素的平均长度

我正在尝试获取我的字符串数组中每个元素的平均长度。但是不确定我的代码。有什么建议么?

public static double averageLength(String[] words, int count) {

    double countedLength = 0.0;


    for(int i = 0; i < words.length; i++) {
        countedLength += words[i].length();
        count++;
    }

    return (double)countedLength / count;
}

展开
收起
小六码奴 2019-10-03 19:37:05 879 分享 版权
1 条回答
写回答
取消 提交回答
  • 也可以将Stream API用于此任务:

    public static double averageLength(String[] words) { return Arrays.stream(words) .mapToDouble(String::length) .average() .getAsDouble(); }

    2019-10-09 15:43:28
    赞同 展开评论
问答地址: