“How would we use jump expressions inside nested loops?” Good question! The answer is labeled jump expressions. By adding a label to the outer loop of nested loops, we can execute a jump expression from the inner loop and have it act on the labeled outer loop.
First we need to give a name to our label. In the following example we choose the name
rps. The outer loop is marked using our label
rps followed by the
The inner loop has an
if expression that contains a
break expression with
@rps appended. When the condition,
p1 == "Paper" is
[email protected] executes and exits the outer loop:
Rock vs. Rock Rock vs. Paper Rock vs. Scissor
Now let’s look at what happens in our example when we change the
break expression to a
What we see now is the outer loop skips an iteration when
p1 == "Paper" but resumes with the final iteration when
p1 is equal to “Scissor”:
Rock vs. Rock Rock vs. Paper Rock vs. Scissor Scissor vs. Rock Scissor vs. Paper Scissor vs. Scissor
Labeled jump expressions give us more control over nested loops to help us achieve the desired behavior from our code. Using them can be tricky, but once understood they can be very powerful.
Recall the 6x6 grid with “A1” to “F6”” cells from the previous exercise. We’ll take a closer look at how we can manipulate the structure and output of this grid using labeled jump expressions.
First, add a label
grid to the outer loop.
if expression inside the inner loop, before the
print("$j$i ") statement. Have the condition test if the inner loop variable is equal to
if expression add a
continue expression that jumps to the
Once you run the code you should see a single line of output. The outer loop numbers go from
6, but the inner loop letters only go up through
It is important to note that the
println() statement at the end of the outer loop is also skipped. The result is only one row is printed. This shows that a labeled
continue will skip any code proceeding it in the inner loop and at the end of the outer loop.