我试图获取字符串数组中每个元素的平均长度。但不确定我的代码。有什么建议么?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; }
3 回答

慕沐林林
TA贡献2016条经验 获得超9个赞
您还可以使用 Stream API 来执行此任务:
public static double averageLength(String[] words) { return Arrays.stream(words) .mapToDouble(String::length) .average() .getAsDouble(); }

精慕HU
TA贡献1845条经验 获得超8个赞
求平均值时,您需要除以求和的元素数量。此外,在您的方法中,您不需要传递count变量,因为您的方法中未使用它。
public static double averageLength(String[] words) {
double countedLength = 0.0;
for(int i = 0; i < words.length; i++) {
countedLength += words[i].length();
}
return countedLength / words.length;
}
出于兴趣,您也可以始终使用foreach循环结构来迭代元素:
public static double averageLength(String[] words) {
int countedLength = 0;
for(String word : words) {
countedLength += word.length();
}
return countedLength / words.length;
}
然而结果是一样的。
添加回答
举报
0/150
提交
取消