Continue the loop in Java


With the continue statement we can stop the current iteration of the loop, and continue with the next.

When Java hits continue, it skips (not execute) any code left, and jumps directly to the next iteration instead.

In this example, we will not let anyone inside a bar if their age is less than 21:

int[] ages = {10, 30, 21, 19, 25};

for (int age : ages) {
	if (age < 21) {
		continue;
	}
	System.out.println("Someone of age " + age + " entered the bar.");
}

The output of this program is:

Someone of age 30 entered the bar.
Someone of age 21 entered the bar.
Someone of age 25 entered the bar.

As you can see, our program doesn't print for ages 10 and 19.

Here's what happens during this loop:

1. First iteration:
	a. age = 10
	b. Is age < 21? Yes:
	    continue => Go directly to the next age
	
2. Second iteration:
	a. age = 30
	b. Is age < 21? No.
	c. System.out.println
	
3. Third iteration:
	a. age = 21
	b. Is age < 21? No.
	c. System.out.println

4. Forth iteration:
	a. age = 19
	b. Is age < 21? Yes:
	    continue => Go directly to the next age
      
5. Fifth iteration:
	a. age = 25
	b. Is age < 21? No.
	c. System.out.println

Assignment
Let's allow only the people with height at least 170 into the arena.


Hint
Look at the examples above if you get stuck.


Introduction

The continue statement in Java is a powerful tool for controlling the flow of loops. It allows you to skip the current iteration and proceed directly to the next one. This can be particularly useful in scenarios where certain conditions need to be met before executing the rest of the loop's code. Understanding how to use continue effectively can help you write cleaner and more efficient code.

Understanding the Basics

The continue statement is used within loops to skip the remaining code in the current iteration and move to the next iteration. This is different from the break statement, which terminates the loop entirely. Here's a simple example to illustrate:

for (int i = 0; i < 10; i++) {
    if (i % 2 == 0) {
        continue; // Skip even numbers
    }
    System.out.println(i);
}

In this example, the loop prints only odd numbers between 0 and 9. The continue statement skips the even numbers.

Main Concepts

The key concept behind the continue statement is to control the flow of the loop based on specific conditions. This can be particularly useful in scenarios where you want to filter out certain values or conditions without breaking the loop entirely. Let's apply this concept to the given problem where we only allow people with a height of at least 170 cm into an arena.

Examples and Use Cases

Consider an array of heights:

int[] heights = {160, 172, 168, 180, 175};

for (int height : heights) {
    if (height < 170) {
        continue; // Skip heights less than 170
    }
    System.out.println("Someone with height " + height + " entered the arena.");
}

The output of this program will be:

Someone with height 172 entered the arena.
Someone with height 180 entered the arena.
Someone with height 175 entered the arena.

As you can see, the program skips heights less than 170 and only prints the heights that meet the condition.

Common Pitfalls and Best Practices

One common mistake when using the continue statement is forgetting that it skips the rest of the code in the current iteration. This can lead to unexpected behavior if you have important code after the continue statement. Always ensure that the continue statement is used appropriately and that any necessary code is placed before it.

Best practices include:

Advanced Techniques

In more complex scenarios, you might use the continue statement in nested loops or with labeled loops. Labeled loops allow you to specify which loop to continue, which can be useful in multi-level nested loops.

outerLoop:
for (int i = 0; i < 5; i++) {
    for (int j = 0; j < 5; j++) {
        if (j == 3) {
            continue outerLoop; // Skip to the next iteration of the outer loop
        }
        System.out.println("i = " + i + ", j = " + j);
    }
}

In this example, when j equals 3, the continue outerLoop statement skips to the next iteration of the outer loop.

Code Implementation

Let's implement the solution for the given assignment:

public class ArenaEntry {
    public static void main(String[] args) {
        int[] heights = {160, 172, 168, 180, 175};

        for (int height : heights) {
            if (height < 170) {
                continue; // Skip heights less than 170
            }
            System.out.println("Someone with height " + height + " entered the arena.");
        }
    }
}

This code will only print the heights of people who are allowed into the arena, effectively demonstrating the use of the continue statement.

Debugging and Testing

When debugging code that uses the continue statement, it's important to ensure that the conditions for skipping iterations are correct. You can use print statements or a debugger to check the values of variables and the flow of the loop.

For testing, you can create various test cases with different arrays of heights to ensure that the code behaves as expected. For example:

public class ArenaEntryTest {
    public static void main(String[] args) {
        testArenaEntry(new int[]{160, 172, 168, 180, 175});
        testArenaEntry(new int[]{150, 160, 170, 180, 190});
        testArenaEntry(new int[]{180, 190, 200});
    }

    public static void testArenaEntry(int[] heights) {
        for (int height : heights) {
            if (height < 170) {
                continue;
            }
            System.out.println("Someone with height " + height + " entered the arena.");
        }
        System.out.println("Test completed.\n");
    }
}

Thinking and Problem-Solving Tips

When approaching problems that involve the continue statement, consider the following strategies:

Conclusion

The continue statement is a valuable tool for controlling the flow of loops in Java. By understanding how to use it effectively, you can write cleaner and more efficient code. Remember to use it judiciously and always ensure that your conditions for skipping iterations are clear and well-documented.

Additional Resources