Jyle Villagracia
Jyle Villagracia

Reputation: 29

Average length of every element in string array

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

Answers (3)

issverg
issverg

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

Ambro-r
Ambro-r

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

Martin&#39;sRun
Martin&#39;sRun

Reputation: 542

Change return to

 return (double)countedLength / words.length;

Upvotes: 0

Related Questions