The continue
statement has two forms, the unlabeled and labeled continue
statement. The first example shows you how to use the unlabeled continue
statement while the second example shows you how to use the labeled continue
statement.
package org.kodejava.basic;
public class ContinueDemo {
public static void main(String[] args) {
int[] numbers = {5, 11, 3, 9, 12, 15, 4, 7, 6, 17};
int counter = 0;
for (int number : numbers) {
// When number is greater or equals to 10 skip the
// current loop and continue to the next loop because
// we only interested to count number less than 10.
if (number >= 10) {
continue;
}
counter++;
}
System.out.println("Found " + counter + " numbers less than 10.");
// The example below used a labeled continue statement. In the
// loop below we sum the number in the array until reminder of
// the number divided by 2 equals to zero. We skip to the next
// array if the reminder is 0.
int[][] values = {
{8, 2, 1},
{3, 3},
{3, 4, 5},
{5, 4},
{6, 5, 2}};
int total = 0;
outer:
for (int[] value : values) {
for (int item : value) {
if (item % 2 == 0) {
continue outer;
}
total += item;
}
}
System.out.println("Total = " + total);
}
}
The output of the code snippet:
Found 6 numbers less than 10.
Total = 14
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024