杰瑞科技汇

break和continue在Java中如何使用?

Of course! Let's break down the break and continue statements in Java. They are both used to alter the normal flow of a loop, but they do so in very different ways.

break和continue在Java中如何使用?-图1
(图片来源网络,侵删)

The Big Picture: Why Use Them?

Imagine you're driving on a road (the loop). Normally, you drive from the start to the end, following every turn (iteration).

  • break is like taking an exit ramp. You immediately stop driving on the current road and get off.
  • continue is like skipping a speed bump. You slow down for a moment but then get right back on the road and continue driving to the next turn.

The break Statement

The break statement is used to terminate a loop or a switch statement immediately. When the break is executed, the program jumps to the first line of code immediately following the loop or switch.

How it Works in a Loop

When break is encountered inside a loop, the loop stops completely, and the execution continues with the statement after the loop.

Example: Finding a Divisor

Let's say we want to find the first number that divides 100 without a remainder.

break和continue在Java中如何使用?-图2
(图片来源网络,侵删)
public class BreakExample {
    public static void main(String[] args) {
        int number = 100;
        boolean found = false;
        System.out.println("Searching for the first divisor of " + number + "...");
        // Loop from 2 up to number-1
        for (int i = 2; i < number; i++) {
            System.out.println("Checking if " + i + " is a divisor...");
            // If the remainder is 0, we found a divisor
            if (number % i == 0) {
                System.out.println("Found it! " + i + " is a divisor.");
                found = true;
                break; // Exit the loop immediately
            }
        }
        if (!found) {
            System.out.println("No divisors found in the checked range.");
        }
    }
}

Output:

Searching for the first divisor of 100...
Checking if 2 is a divisor...
Found it! 2 is a divisor.

Explanation: The loop starts checking from i = 2. It finds that 100 % 2 == 0, so the if condition is true. The break statement is executed, and the for loop terminates immediately. The program then skips to the line after the loop.


The continue Statement

The continue statement is used to skip the current iteration of a loop and immediately jump to the next iteration.

How it Works in a Loop

When continue is encountered, the code inside the loop for the current iteration stops executing. The loop's update expression (e.g., i++ in a for loop) is executed, and then the condition is checked again. If the condition is still true, the next iteration begins.

break和continue在Java中如何使用?-图3
(图片来源网络,侵删)

Example: Printing Odd Numbers Only

Let's print all numbers from 1 to 10, but only the odd ones.

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) {
                continue; // Skip this iteration and go to the next one
            }
            // 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

Explanation: The loop runs from i = 1 to i = 10.

  • When i is 1, 1 % 2 is not 0, so continue is skipped. System.out.println is executed.
  • When i is 2, 2 % 2 is 0, so continue is executed. The rest of the loop body for this iteration is skipped. The loop increments i to 3 and starts the next iteration.
  • This pattern continues, and only odd numbers are printed.

Key Differences: break vs. continue

Feature break continue
Action Exits the loop entirely. Skips the rest of the current iteration.
Flow Control Jumps to the statement after the loop. Jumps to the next iteration of the loop.
Analogy Taking an exit ramp off a highway. Skipping a pothole and continuing to drive.
Use Case To stop searching when a condition is met (e.g., found an item). To skip a specific case (e.g., don't process negative numbers).

Advanced: Labeled break and continue

You can use labels to control break and continue in nested loops. This is a more advanced feature but can be very useful in complex situations.

A label is simply an identifier followed by a colon () placed before a loop.

Labeled break

This allows you to break out of a specific outer loop, not just the innermost one.

public class LabeledBreak {
    public static void main(String[] args) {
        outerLoop: // This is the label for the outer loop
        for (int i = 1; i <= 3; i++) {
            for (int j = 1; j <= 3; j++) {
                System.out.println("i: " + i + ", j: " + j);
                if (i == 2 && j == 2) {
                    System.out.println("Breaking out of both loops!");
                    break outerLoop; // Breaks the outerLoop, not just the inner one
                }
            }
        }
        System.out.println("Program finished.");
    }
}

Output:

i: 1, j: 1
i: 1, j: 2
i: 1, j: 3
i: 2, j: 1
i: 2, j: 2
Breaking out of both loops!
Program finished.

Without the label, break; would have only terminated the inner j loop. The i loop would have continued to i = 3.

Labeled continue

This allows you to skip to the next iteration of a specific outer loop.

public class LabeledContinue {
    public static void main(String[] args) {
        outerLoop:
        for (int i = 1; i <= 3; i++) {
            for (int j = 1; j <= 3; j++) {
                if (i == 2 && j == 2) {
                    System.out.println("(i=2, j=2) - Skipping to next i iteration.");
                    continue outerLoop; // Skips the rest of the current i iteration
                }
                System.out.println("i: " + i + ", j: " + j);
            }
        }
    }
}

Output:

i: 1, j: 1
i: 1, j: 2
i: 1, j: 3
i: 2, j: 1
(i=2, j=2) - Skipping to next i iteration.
i: 3, j: 1
i: 3, j: 2
i: 3, j: 3

Explanation: When i is 2 and j is 2, continue outerLoop is executed. This means the inner loop for j is terminated, and the i loop immediately starts its next iteration (i becomes 3). The j = 2 and j = 3 iterations for i = 2 are skipped.

Best Practices

  • Use Sparingly: Overusing break and continue can make your code harder to read and follow. It's often better to structure your loop's condition to avoid needing them.
  • Prefer a Clear Condition: Instead of using break to exit a loop, try to write the for or while condition so that it becomes false naturally.
    • Instead of:
      for (int i = 0; ; i++) {
          if (i > 100) break;
          // ...
      }
    • Do this:
      for (int i = 0; i <= 100; i++) {
          // ...
      }
  • Use Labels Judiciously: Labeled break and continue can be confusing. Only use them when they make the code significantly clearer than a more complex nested if-else structure.
分享:
扫描分享到社交APP
上一篇
下一篇