杰瑞科技汇

java break while

Of course! Let's break down how to use the break statement with a while loop in Java.

The Core Idea

The break statement in Java is a control flow statement that allows you to exit a loop prematurely. When the break statement is executed inside a loop, the loop immediately terminates, and the program continues executing the code that comes immediately after the loop.

This is useful when you've found the item you were looking for or when a certain condition makes it pointless to continue iterating.


break in a Simple while Loop

This is the most straightforward use case. You have a while loop, and based on a condition inside the loop, you decide to exit.

Example: Finding a Specific Number

Let's say we want to search through numbers and stop as soon as we find the number 50.

public class WhileBreakExample {
    public static void main(String[] args) {
        int number = 1;
        System.out.println("Starting the search...");
        // This loop will run indefinitely until we break out of it
        while (true) { // Note: Using 'while (true)' creates an infinite loop
            System.out.println("Checking number: " + number);
            // The condition to break the loop
            if (number == 50) {
                System.out.println("Found it! Breaking the loop.");
                break; // Exit the while loop immediately
            }
            number++; // Increment the number for the next iteration
        }
        System.out.println("Loop has finished. The search is over.");
    }
}

Output:

Starting the search...
Checking number: 1
Checking number: 2
...
Checking number: 48
Checking number: 49
Checking number: 50
Found it! Breaking the loop.
Loop has finished. The search is over.

Explanation:

  1. The while (true) creates an infinite loop.
  2. Inside the loop, we check if number is 50.
  3. The first 49 times, the condition number == 50 is false, so the loop continues.
  4. When number becomes 50, the condition is true. The break statement is executed.
  5. The while loop is instantly terminated, and the program jumps to the line immediately after the closing curly brace of the loop (System.out.println("Loop has finished...");).

break with Labeled Loops (Breaking an Outer Loop)

Sometimes you have nested loops (a loop inside another loop), and you want to break out of the outer loop from inside the inner loop. The standard break can only break out of the innermost loop it's in.

To solve this, you can use labeled loops. You give a name (a label) to the outer loop and then use break labelName; to exit it.

Example: Breaking an Outer Loop

Let's imagine we're searching for a specific coordinate (x, y) in a grid. Once we find it, we want to stop searching completely.

public class LabeledWhileBreakExample {
    public static void main(String[] args) {
        int targetX = 3;
        int targetY = 2;
        // Label the outer loop
        outerLoop:
        while (true) {
            int x = 0;
            while (x < 5) {
                System.out.println("Checking coordinate: (" + x + ", " + targetY + ")");
                if (x == targetX) {
                    System.out.println("Target X found at " + x + "! Breaking all loops.");
                    break outerLoop; // Breaks the loop labeled 'outerLoop'
                }
                x++;
            }
            // This line will never be reached because of the labeled break
            System.out.println("Finished checking a row. Moving to the next...");
        }
        System.out.println("All search loops have terminated.");
    }
}

Output:

Checking coordinate: (0, 2)
Checking coordinate: (1, 2)
Checking coordinate: (2, 2)
Checking coordinate: (3, 2)
Target X found at 3! Breaking all loops.
All search loops have terminated.

Explanation:

  1. We have an outerLoop labeled with outerLoop:.
  2. Inside it, we have an inner while loop for the x-coordinate.
  3. When x becomes 3, the condition x == targetX is met.
  4. break outerLoop; is executed. This doesn't just break the inner while loop; it breaks the outerLoop that we specified.
  5. The program jumps directly to the code after the outerLoop.

break vs. continue

It's crucial not to confuse break with continue.

Keyword Action Effect on Loop
break Terminates the loop entirely. The loop stops, and the program continues after the loop's closing brace.
continue Skips the rest of the current iteration. The loop immediately jumps to the next iteration (it checks the loop condition and starts the next cycle).

Example: break vs. continue

public class BreakVsContinue {
    public static void main(String[] args) {
        System.out.println("--- Demonstrating 'break' ---");
        int i = 1;
        while (i <= 5) {
            if (i == 3) {
                break; // Exit the loop completely when i is 3
            }
            System.out.println("break: " + i);
            i++;
        }
        System.out.println("Loop with 'break' is finished.\n");
        System.out.println("--- Demonstrating 'continue' ---");
        int j = 1;
        while (j <= 5) {
            if (j == 3) {
                j++; // IMPORTANT: Increment j to avoid an infinite loop!
                continue; // Skip the rest of the code for this iteration when j is 3
            }
            System.out.println("continue: " + j);
            j++;
        }
        System.out.println("Loop with 'continue' is finished.");
    }
}

Output:

--- Demonstrating 'break' ---
break: 1
break: 2
Loop with 'break' is finished.
--- Demonstrating 'continue' ---
continue: 1
continue: 2
continue: 4
continue: 5
Loop with 'continue' is finished.

Notice how with continue, the value 3 is skipped, but the loop continues until its natural end.

Summary

Use Case How to Do It Example
Exit a single while loop Use break; inside an if condition. if (condition) { break; }
Exit an outer while loop from an inner loop Label the outer loop and use break labelName;. outer: while (...) { ... if (cond) { break outer; } ... }
Skip to the next iteration Use continue; inside an if condition. if (condition) { continue; }
分享:
扫描分享到社交APP
上一篇
下一篇