-1
public int wordsCount(String[] words, int len) {
    int counter = 0;
    for (String s : words) {
    if (s.length()==len) {
    counter++;
    } 
    
  }
  return counter;
  
}

Here I am trying to find the number of strings and the length of the inputs given

Jennifer
  • 13
  • 5

2 Answers2

0

The loop you have used is the for each loop inside your function wordsCount.

What the for each loop does is, traverse the whole array based on the underlying data type of the array.So you don't have to create a loop counter to traverse, rather, as in your case String s will be used to traverse the String array where s is your current element in the array.

The syntax: for ([Data type][variable] : [source array/iterable])

Niresh
  • 67
  • 7
0

The colon does nothing, aside from allowing your code to compile!

: is just part of the syntax of the enhanced for statement, also less-formally known as the "for each loop".

As it says in the "for each loop" link above:

void cancelAll(Collection<TimerTask> c) {
    for (TimerTask t : c)
        t.cancel();
}

When you see the colon (:) read it as "in." The loop above reads as "for each TimerTask t in c."

So, applying the same interpretation to your code, read it as "for each String s in words".

Andy Turner
  • 137,514
  • 11
  • 162
  • 243