continue,break
2068 ワード
The break and continue keywords are used to stop either the entire loop
(break) or just the current iteration (continue).
Output:
Inside loop, i = 0 after the if statement, still inside loop Inside loop, i = 1 after the if statement, still inside loop Inside loop, i = 2 after the if statement, still inside loop Inside loop, i = 3 if is true: i == 3 Inside loop, i = 4 after the if statement, still inside loop out of loop
Output:
Inside loop, i = 0 after the if statement, still inside loop Inside loop, i = 1 after the if statement, still inside loop Inside loop, i = 2 after the if statement, still inside loop Inside loop, i = 3 if is true: i == 3 out of loop
(break) or just the current iteration (continue).
public class ForLoop {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.println("Inside loop, i = "+i);
if (i == 3) {
System.out.println("if is true: i == 3");
continue;
// compile error: says it's unreachable
// System.out.println("after the continue statement");
}
// more loop code, that won't be reached when the above if test is true
System.out.println("after the if statement, still inside loop");
}
System.out.println("out of loop");
}
}
Output:
Inside loop, i = 0 after the if statement, still inside loop Inside loop, i = 1 after the if statement, still inside loop Inside loop, i = 2 after the if statement, still inside loop Inside loop, i = 3 if is true: i == 3 Inside loop, i = 4 after the if statement, still inside loop out of loop
public class ForLoop {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.println("Inside loop, i = "+i);
if (i == 3) {
System.out.println("if is true: i == 3");
break;
// compile error: says it's unreachable
// System.out.println("after the continue statement");
}
// more loop code, that won't be reached when the above if test is true
System.out.println("after the if statement, still inside loop");
}
System.out.println("out of loop");
}
}
Output:
Inside loop, i = 0 after the if statement, still inside loop Inside loop, i = 1 after the if statement, still inside loop Inside loop, i = 2 after the if statement, still inside loop Inside loop, i = 3 if is true: i == 3 out of loop