Reputation: 29
I'm trying to get an average length of every element in my string array. But not sure with my code. Any suggestions?
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;
}
Upvotes: 1
Views: 1597
Reputation: 80
You can also use Stream API for this task:
public static double averageLength(String[] words) {
return Arrays.stream(words)
.mapToDouble(String::length)
.average()
.getAsDouble();
}
Upvotes: 2
Reputation: 929
When you average you need to divide by the number of elements you've summed up. Also in your method you don't need to pass the count
variable as it's not used in your method.
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;
}
Just out of interest, you could always also use the foreach
loop structure to iterate through the elements:
public static double averageLength(String[] words) {
int countedLength = 0;
for(String word : words) {
countedLength += word.length();
}
return countedLength / words.length;
}
The result is the same however.
Upvotes: 0
Reputation: 542
Change return to
return (double)countedLength / words.length;
Upvotes: 0