开发者社区 问答 正文

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

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

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 859 分享
分享
版权
举报
1 条回答
写回答
取消 提交回答
  • 也可以将Stream API用于此任务:

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

    2019-10-09 15:43:28 举报
    赞同 评论

    评论

    全部评论 (0)

    登录后可评论
问答地址:
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等