The for-each loop

If you use an array for any part of your game-state model, then it is almost certain you will need to iterate over it (i.e., perform some operation for each element) for some reason or another. You may need to look for a certain value, or count the number of values that satisfy a certain condition, or, if the values are numbers, add them all up, or simply display all the values. The for-each loop was designed for this purpose.

Suppose words is a String array containing a sentence's words. You could print each word with this loop:

for (String word : words) {
   System.out.println(word);
}

This for loop executes the body—System.out.println(word)—once for each element in words. So if words contained “My”, “dog”, “has”, “fleas”, this code would result in:

My
dog
has
fleas

As a template:

for ( type var : arr ) {
      body
}

  • type must agree with the type of arr's elements;
  • body is zero or more statements;
  • The statements in body are executed once for each element in arr;
  • For each execution of body, the array element is put into the variable var.

Here's a loop that computes the average of the numbers in scores:

double sum = 0.0;
for (double score : scores) {
   sum += score;
}
double average = sum / scores.length;