Java Reference
In-Depth Information
};
int pawns = 0;
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if (!pieces[i][j].contains("Pawn")) {
continue;
}
pawns++;
}
}
System.out.println("Surviving pawns: " + pawns);
When we
encounter
the
continue
statement, we jump over any other code in the loop and process
the next item.
Note that we can rewrite the body of the inner loop to not use a
continue
statement as in Listing
5-18:
Listing 5-18. Doing without the
continue
statement
if (pieces[i][j].contains("Pawn")) {
pawns++;
}
It turns out that writing an example of the
continue
statement that can't be rewritten to be simpler
without the
continue
statement is fairly hard to do, which is why
continue
statements don't appear in
code that often.
Like the
break
statement, the
continue
statement can use a label. As it happens, adding a label to a
continue
statement in the chess example yields the same result, though with more processing. So let's
consider an example that counts the number of characters that appear before the first space in each
string within an array of strings (see Listing 5-19).
Listing 5-19. A continue statement with a label
String[] detectives = {"Sam Spade", "Sherlock Holmes", "Charlie Chan"};
int charactersBeforeSpaces = 0;
outer:
for (String str : detectives) {
char[] strChars = str.toCharArray();
for (char ch : strChars) {
if (ch == ' ') {
continue outer;
}
charactersBeforeSpaces++;
}
}
System.out.println(charactersBeforeSpaces);
This bit of code prints 18.