我試圖獲取字符串數組中每個元素的平均長度。但不確定我的代碼。有什么建議么?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
提交
取消