Java中的break语句,标签
Java的break语句用于在处理过程中终止循环。我们在Java程序中使用break保留关键字来跳出循环。
Java中的break
有两种形式的break语句 – 无标签和有标签。大多数情况下,break语句用于根据某些条件终止循环,例如当达到退出命令时中止处理。无标签的break语句用于终止包含它的循环,并可与switch、for、while和do-while循环一起使用。
在Java示例中打断
以下是一个示例,展示了在Java中如何使用break语句来中断for循环、while循环和do-while循环。
package com.Olivia.util;
package com.Olivia.util;
public class JavaBreak {
public static void main(String[] args) {
String[] arr = { "A", "E", "I", "O", "U" };
// find O in the array using for loop
for (int len = 0; len < arr.length; len++) {
if (arr[len].equals("O")) {
System.out.println("Array contains 'O' at index: " + len);
// break the loop as we found what we are looking for
break;
}
}
// use of break in while loop
int len = 0;
while (len < arr.length) {
if (arr[len].equals("E")) {
System.out.println("Array contains 'E' at index: " + len);
// break the while loop as we found what we are looking for
break;
}
len++;
}
len = 0;
// use of break in do-while loop
do {
if (arr[len].equals("U")) {
System.out.println("Array contains 'U' at index: " + len);
// break the while loop as we found what we are looking for
break;
}
len++;
} while (len < arr.length);
}
}
Java 中的 break label可以被替换为以下的方式:
标记的break语句用于终止外循环,循环必须被标记才能起作用。下面是一个示例展示Java中的break标签语句的使用。
package com.Olivia.util;
public class JavaBreakLabel {
public static void main(String[] args) {
int[][] arr = { { 1, 2 }, { 3, 4 }, { 9, 10 }, { 11, 12 } };
boolean found = false;
int row = 0;
int col = 0;
// find index of first int greater than 10
searchint:
for (row = 0; row < arr.length; row++) {
for (col = 0; col < arr[row].length; col++) {
if (arr[row][col] > 10) {
found = true;
// using break label to terminate outer statements
break searchint;
}
}
}
if (found)
System.out.println("First int greater than 10 is found at index: [" + row + "," + col + "]");
}
}