Java OCA考试备考:if语句使用continue的编译疑问
break/continue in if Statements for OCA Exam Hey there! Let's clear up this confusion you're having—it's a common point that trips up many OCA candidates, so great catch on noticing the discrepancy!
First, let's unpack what Sybex's Table 2.5 actually means
The note says "if语句不允许使用break、continue语句" (if statements don't allow break/continue), but this is referring to using break/continue to target the if statement itself. Since if is a conditional branching structure (not a loop or switch), there's no structure for break/continue to interrupt here. For example, this code would fail to compile:
public class BadExample { public static void main(String[] args) { int x = 5; if (x > 0) { break; // Compile error: no enclosing loop or switch statement } } }
Here, break has no loop or switch to act on—this is the scenario Sybex is warning about.
Now let's look at your sample code
Your code has continue nested inside an if, but crucially, that if is itself inside a while loop (the inner while(y>0) loop). The continue here doesn't target the if statement—it targets the nearest enclosing loop (the inner while loop).
Let's break down how this works:
- When
x < 2is true,continueskips the rest of the inner loop's iteration (sox--,y--, and theSystem.out.printlndon't run) and jumps back to the start of the innerwhile(y>0)condition check. - Since
continueis clearly associated with a valid loop structure, the compiler has no issue with this code.
Key Takeaway for OCA
Remember: break and continue only require an enclosing loop or switch statement to be valid. They can be nested inside if blocks, as long as they're still within a loop/switch that they can act on. The Sybex note is just warning you not to use them without that enclosing loop/switch, or to try using them to control the if itself.
内容的提问来源于stack exchange,提问作者Sam

