杰瑞科技汇

Java中continue的作用和用法是什么?

Of course! In Java, the continue keyword is a control flow statement used inside loops (like for, while, or do-while). Its purpose is to skip the rest of the current iteration of the loop and immediately jump to the next iteration.

Java中continue的作用和用法是什么?-图1
(图片来源网络,侵删)

Think of it like saying, "Okay, I'm done with this specific round of the loop. Let's start the next one right away."


How continue Works in a for Loop

The for loop is the most common place to see continue. Let's look at a simple example.

Basic Example: Skipping Even Numbers

Imagine you want to print all numbers from 1 to 10, but you want to skip the even numbers.

Without continue:

Java中continue的作用和用法是什么?-图2
(图片来源网络,侵删)
for (int i = 1; i <= 10; i++) {
    if (i % 2 != 0) { // If the number is odd
        System.out.println(i);
    }
}
// Output:
// 1
// 3
// 5
// 7
// 9

This works, but it's not very efficient. The System.out.println() is only called when the condition is true.

With continue: This approach is often cleaner and more direct. The logic is: "If the number is even, skip the rest of the loop body and go to the next number."

public class ContinueExample {
    public static void main(String[] args) {
        System.out.println("Printing odd numbers from 1 to 10:");
        for (int i = 1; i <= 10; i++) {
            // Check if the number is even
            if (i % 2 == 0) {
                // If it is, skip the rest of this iteration
                continue;
            }
            // This line will only be reached for odd numbers
            System.out.println("Current number: " + i);
        }
    }
}

Output:

Printing odd numbers from 1 to 10:
Current number: 1
Current number: 3
Current number: 5
Current number: 7
Current number: 9

Step-by-step breakdown:

Java中continue的作用和用法是什么?-图3
(图片来源网络,侵删)
  1. i = 1: 1 % 2 == 0 is false. The if block is skipped. System.out.println is executed. Output: Current number: 1.
  2. i = 2: 2 % 2 == 0 is true. The if block is executed. continue is called. The rest of the loop body (the System.out.println) is skipped. The loop immediately increments i to 3 and checks the condition.
  3. i = 3: 3 % 2 == 0 is false. The if block is skipped. System.out.println is executed. Output: Current number: 3.
  4. ...and so on.

continue in while and do-while Loops

The behavior is the same, but you have to be careful with while and do-while loops. continue jumps to the loop's condition, not to the increment/decrement part.

Example: while Loop

Let's say we want to find the first number between 1 and 10 that is divisible by 3.

public class ContinueWhileExample {
    public static void main(String[] args) {
        int i = 1;
        System.out.println("Searching for the first number divisible by 3...");
        while (i <= 10) {
            if (i % 3 != 0) {
                // If not divisible by 3, skip to the next number
                i++; // IMPORTANT: You must manually increment here!
                continue;
            }
            System.out.println("Found it! The number is: " + i);
            break; // Exit the loop since we found our number
        }
    }
}

Output:

Searching for the first number divisible by 3...
Found it! The number is: 3

Why i++ is crucial: If you forget i++ inside the if block, i would never change. When i is 1, the condition 1 % 3 != 0 is true, continue is called, and the program jumps back to while (i <= 10). Since i is still 1, this creates an infinite loop.

Example: do-while Loop

The same logic applies here. The continue statement will cause the program to jump to the while condition at the end of the loop.


Labeled continue (Advanced)

Sometimes you have nested loops, and you want to break out of the current iteration of an outer loop. For this, you can use a labeled continue.

First, you label the outer loop with a name followed by a colon. Then, you use continue labelName; to jump to the next iteration of that specific labeled loop.

Example: Skipping a Whole Row in a Nested Loop

Imagine you're processing a 2D grid (a 3x3 matrix). You want to skip an entire row if the first element of that row is 0.

public class LabeledContinueExample {
    public static void main(String[] args) {
        int[][] matrix = {
            {0, 1, 2},
            {3, 4, 5},
            {0, 7, 8}
        };
        // Label the outer loop
        outerLoop:
        for (int i = 0; i < matrix.length; i++) {
            System.out.println("\nProcessing row " + i + ":");
            // Check the first element of the row
            if (matrix[i][0] == 0) {
                System.out.println("  -> Skipping this row because the first element is 0.");
                continue outerLoop; // Skip to the next iteration of the outerLoop
            }
            // This code will only run for rows that don't start with 0
            for (int j = 0; j < matrix[i].length; j++) {
                System.out.print("  " + matrix[i][j]);
            }
        }
    }
}

Output:

Processing row 0:
  -> Skipping this row because the first element is 0.
Processing row 1:
  3  4  5
Processing row 2:
  -> Skipping this row because the first element is 0.

Without the outerLoop: label, a simple continue; would only skip the current iteration of the inner for loop, not the entire row.


continue vs. break

This is a very common point of confusion.

Feature continue break
Purpose Skips the rest of the current iteration and starts the next one. Exits the entire loop immediately.
Effect Jumps to the loop's condition (or increment part in a for loop). Jumps to the code immediately after the loop.
Use Case "I want to ignore this specific item and move on to the next one." "I'm done with this loop entirely. I found what I was looking for or a problem occurred."

Example: break

for (int i = 1; i <= 10; i++) {
    if (i == 5) {
        break; // Exit the loop completely when i is 5
    }
    System.out.println(i);
}
// Output:
// 1
// 2
// 3
// 4
// The loop stops here. 5, 6, 7, 8, 9, 10 are never printed.

Summary

Keyword Action Use Case
continue Skips to the next iteration of the loop. Filtering data (e.g., skipping negative numbers), handling edge cases.
break Exits the loop entirely. Finding an item in a list, terminating a loop when a condition is met.
return Exits the entire method. When a method's main goal is achieved or a critical error occurs.
分享:
扫描分享到社交APP
上一篇
下一篇