Java break 语句用于在其处理之间终止循环,我们使用break
备用关键字在 java 程序中解除循环。
Java 打破
有两种形式的中断声明 - unlabeled和 labeled. 大多数中断声明用于根据某些条件终止循环,例如如果达到输出命令时断处理。
打破在Java的例子
以下是一個示例,顯示 java break 聲明的使用為 loop,而 loop 和 do-while loop。
1package com.journaldev.util;
2
3package com.journaldev.util;
4
5public class JavaBreak {
6
7 public static void main(String[] args) {
8 String[] arr = { "A", "E", "I", "O", "U" };
9
10 // find O in the array using for loop
11 for (int len = 0; len < arr.length; len++) {
12 if (arr[len].equals("O")) {
13 System.out.println("Array contains 'O' at index: " + len);
14 // break the loop as we found what we are looking for
15 break;
16 }
17 }
18
19 // use of break in while loop
20 int len = 0;
21 while (len < arr.length) {
22 if (arr[len].equals("E")) {
23 System.out.println("Array contains 'E' at index: " + len);
24 // break the while loop as we found what we are looking for
25 break;
26 }
27 len++;
28 }
29
30 len = 0;
31 // use of break in do-while loop
32 do {
33 if (arr[len].equals("U")) {
34 System.out.println("Array contains 'U' at index: " + len);
35 // break the while loop as we found what we are looking for
36 break;
37 }
38 len++;
39 } while (len < arr.length);
40 }
41
42}
Note that if we remove break statement, there won't be any difference in the output of the program. For small iterations like in this example, there is not much of a performance benefit. But if the iterator size is huge, then it can save a lot of processing time.
Java打破标签
标记破解声明用于终止外部循环,循环应该被标记以便它工作. 这里有一个示例显示 Java 破解标签声明的使用。
1package com.journaldev.util;
2
3public class JavaBreakLabel {
4
5 public static void main(String[] args) {
6 int[][] arr = { { 1, 2 }, { 3, 4 }, { 9, 10 }, { 11, 12 } };
7 boolean found = false;
8 int row = 0;
9 int col = 0;
10 // find index of first int greater than 10
11 searchint:
12
13 for (row = 0; row < arr.length; row++) {
14 for (col = 0; col < arr[row].length; col++) {
15 if (arr[row][col] > 10) {
16 found = true;
17 // using break label to terminate outer statements
18 break searchint;
19 }
20 }
21 }
22 if (found)
23 System.out.println("First int greater than 10 is found at index: [" + row + "," + col + "]");
24 }
25
26}
We can also use break statement to get out of switch-case statement, you can learn about all these in below video. https://www.youtube.com/watch?v=K148NXHD-UM Reference: Oracle Documentation