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. [...]
A labeled continue statement skips the current iteration of an outer loop marked with the given label.
A. Use a simple continue statement in Java
Continue_Ex1.java
public class Continue_Ex1 {
public static void main(String args[]) {
for(int i=1; i<=3 ; i++) {
for(int j=0 ; j<3 j="" span="">3>
if(j == 2)
continue;
System.out.println("i : " + i + ", j : " + j);
}
}
}
}
Sample Output
i : 1, j : 0
i : 1, j : 1
i : 2, j : 0
i : 2, j : 1
i : 3, j : 0
i : 3, j : 1
B. Use continue statement with a label in Java
Continue_Ex2.java
public class Continue_Ex2 {
public static void main(String args[]) {
outer:
for(int i=1; i<=3 ; i++) {
for(int j=0 ; j<3 j="" span="">3>
if(j == 2)
continue outer;
System.out.println("i : " + i + ", j : " + j);
}
}
}
}
Sample Output
i : 1, j : 0
i : 1, j : 1
i : 2, j : 0
i : 2, j : 1
i : 3, j : 0
i : 3, j : 1
C. Continue Statement usage in Java
Continue_Ex3.java
public class Continue_Ex3 {
public static void main(String[] args) {
for(int i=0; i<10 i="" nbsp="" span="">10>
System.out.print(i + " ");
if (i%2 == 0)
continue;
System.out.println("");
}
}
}
Sample Output
0 1
2 3
4 5
6 7
8 9
D. Generate Pascal triangle with continue statement in Java
Continue_Ex4.java
public class Continue_Ex4 {
public static void main(String args[]) {
outer:
for (int i=1; i<=5; i++) {
for(int j=1; j<=5; j++) {
if(j > i) {
System.out.println();
continue outer;
}
System.out.print(" " + (i * j));
}
}
System.out.println();
}
}
Sample Output
1
2 4
3 6 9
4 8 12 16
5 10 15 20 25
|
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.