Continue_keyWord ╰半夏微凉° 2021-11-05 06:44 207阅读 0赞 ## Java continue Statement with Examples ## In this quick article, we will discuss how and when to use the continue statement with examples. The continue statement skips the current iteration of a for, while or do-while loop. The unlabeled form skips to the end of the innermost loop’s body and evaluates the boolean expression that controls the loop. ## Table of contents ## Flow Diagram of a continue Statement continue Statement Inside for Loop Example * Using continue Statement in while Loop Example * Using continue Statement in do-while Loop Example * Using continue Statement with Labeled for Loop Syntax continue word followed by a semicolon. continue; ### 1. Flow Diagram of a continue Statement ### ### 2. continue Statement Inside for Loop Example ### package net.javaguides.corejava.controlstatements.loops; public class ContinueExample { public static void main(String args[]) { for (int i = 0; i < 10; i++) { System.out.print(i + " "); if (i % 2 == 0) continue; System.out.println(""); } } } This code uses the % operator to check if i is even. If it is, the loop continues without printing a newline. Here is the output from this program: 0 1 2 3 4 5 6 7 8 9 ### 3. Using continue Statement in while Loop Example ### package net.javaguides.corejava.controlstatements.loops; public class ContinueExample { public static void main(String args[]) { int count = 10; while (count >= 0) { if (count == 7) { count--; continue; } System.out.println(count + " "); count--; } } } Output: 10 9 8 6 5 4 3 2 1 0 Note that we are iterating this loop from 10 to 0 for counter value and when the counter value is 7 the loop skipped the print statement and started the next iteration of the while loop. ### 4. Using continue Statement in do-while Loop Example ### package net.javaguides.corejava.controlstatements.loops; public class ContinueExample { public static void main(String args[]) { int j = 0; do { if (j == 7) { j++; continue; } System.out.print(j + " "); j++; } while (j < 10); } } Output: 0 1 2 3 4 5 6 8 9 Note that we have skipped iteration when j==7. ### 5. Using continue Statement with Labeled for Loop ### As with the break statement, continue may specify a label to describe which enclosing loop to continue. Here is an example program that uses continue to print a triangular multiplication table for 0 through 9: package net.javaguides.corejava.controlstatements.loops; public class ContinueLabel { public static void main(String args[]) { outer: for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { if (j > i) { System.out.println(); continue outer; } System.out.print(" " + (i * j)); } } System.out.println(); } } Output: 0 0 1 0 2 4 0 3 6 9 0 4 8 12 16 0 5 10 15 20 25 0 6 12 18 24 30 36 0 7 14 21 28 35 42 49 0 8 16 24 32 40 48 56 64 0 9 18 27 36 45 54 63 72 81
还没有评论,来说两句吧...