Still Expressing and operating...

This document was written by CS 290W TA Joshua Kay and was last modified

We can use what are known as the break and continue statements. These are used to skip different parts of loops. Let's look:
for(int x=0; x<10; x++) { if (x==5) { break; } else if (x==3) { continue; } g.drawString("x= " +x,10,20+x); } What will this print out?

When x reaches 5, it will break out of the loop. That's what break does. It will just move on to the next portion of the program. When x reaches 3, though, it hits the continue statement and skips the remainder of the loop for that one iteration. So this simple for loop will print out 0,1,2,4.

We also need to (briefly) go over the switch statement. The switch statement is used in place of long groups of if/else statements. Let's just look at an example:

switch(x) { case 0: g.drawString(x,10,20); //will print 0 break; case 1: g.drawString(x,10,35); //will print 1 break; case 2: g.drawString(x,10,50); //will print 2 break; case 3: g.drawString(x,10,65); //will print 3 break; case 4: g.drawString(x,10,80); //will print 4 break; default: g.drawString("",10,95); //will print nothing break; } Be sure to include the break statements in the switch statement as shown above. Otherwise, execution will begin with the matching case and continue through the end of the set of cases.