By Barry Burd

To understand how to nest Java’s enhanced for loops, think about a slot machine. After you’ve written some simple code to determine the outcome, you ask about more complicated problems. “Can I list all possible three-reel combinations of the slot machine’s four symbols?” Yes, you can. This code shows you how to do it.

import static java.lang.System.out;
class ListCombinations {
 enum Symbol {
  cherry, lemon, kumquat, rutabaga
 }
 public static void main(String args[]) {
for (Symbol leftReel : Symbol.values()) {
for (Symbol middleReel : Symbol.values()) {
for (Symbol rightReel : Symbol.values()) {
     out.print(leftReel);
     out.print(" ");
     out.print(middleReel);
     out.print(" ");
     out.println(rightReel);
}
   }
  }
 }
}

When you run this program, you get 64 lines of output.

image0.jpg

This program contains a loop within a loop. In fact, this code has a loop within a loop within a loop. Here’s the strategy:

for (each of the 4 symbols that
  can appear on the left reel),
 for (each of the 4 symbols that
   can appear on the middle reel),
  for (each of the 4 symbols that
    can appear on the right reel),
   display the three reels' symbols.

So you start the outer loop with the cherry symbol. Then you march on to the middle loop and begin that loop with the cherry symbol. Then you proceed to the inner loop and pick the cherry (pun intended). At last, with each loop tuned to the cherry setting, you display the cherry cherry cherry combination.

image1.jpg

After displaying cherry cherry cherry, you continue with other values of the innermost loop. That is, you change the right reel’s value from cherry to lemon. Now the three reels’ values are cherry cherry lemon, so you display these values on the screen.

image2.jpg

After exhausting the four values of the innermost (right reel) loop, you jump out of that innermost loop. But the jump puts you back to the top of the middle loop, where you change the value of middleReel from cherry to lemon. Now the values of leftReel and middleReel are cherry and lemon, respectively.

image3.jpg

Having changed to lemon on the middle loop, you go barreling again into the innermost loop. As if you’d never seen this inner loop before, you set the loop’s variable to cherry.

image4.jpg

After displaying the tasty cherry lemon cherry combination, you start changing the values of the innermost loop.

image5.jpg

The loop keeps going until it displays all 64 combinations. Whew.