break是我们用于退出循环的语句之一。如果在循环中发现break,它将退出循环并执行循环后面的语句。
break:
我们通过一个示例来理解break。
假设我们需要在一个数组中查找一个元素,如果找到该元素,我们则可以使用break退出循环。
package org.loop;
public class BreakStatementDemo {
public static void main(String[] args) {
BreakStatementDemo bse = new BreakStatementDemo();
int arr[] = { 32, 45, 53, 65, 43, 23 };
bse.findElementInArr(arr, 53);
}
public void findElementInArr(int arr[], int elementTobeFound) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == elementTobeFound) {
System.out.println(elementTobeFound + " is present in the array ");
break; // break语句被执行,退出当前循环
}
}
System.out.println("Executing statments following the loop");
}
}
上面程序运行后的结果显示如下:
53 is present in the array
Executing statements following the loop
标签的break
break通常只中断当前循环。假如有多个循环嵌套时,你想要退出嵌套在最外的循环时,你可以使用标签的break语句。
我们通过一个示例来理解它。
示例
假设你想在一个二维数组中找到某一元素。 一旦找到数组中的该元素,则退出外部循环。
package org.loop;
public class LabledBreakDemo {
public static void main(String[] args) {
LabledBreakDemo bse = new LabledBreakDemo();
int arr[][] = { { 32, 45, 35 }, { 53, 65, 67 }, { 43, 23, 76 } };
bse.findElementInArr(arr, 65);
}
public void findElementInArr(int arr[][], int elementTobeFound) {
outer: for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j] == elementTobeFound) {
System.out.println(elementTobeFound + " is present in the array ");
break outer; // labeled break被执行,系统将退出outer for循环
}
}
}
System.out.println("Executing statements following the outer loop");
}
}
程序运行后显示结果如下:
65 is present in the array
Executing statements following the outer loop
Switch Case:
你也可以在switch case中使用break语句。 一旦条件符合,程序将退出switch case。
如下所示:
package org.loop;
public class SwitchCaseDemo {
public static void main(String[] args) {
char vehType = 'C';
switch (vehType) {
case 'B':
System.out.println("BUS");
break;
case 'C':
System.out.println("Car");
break;
case 'M':
System.out.println("Motor cycle");
default:
System.out.println("Invalid vehicle type");
}
System.out.println("Your vehicle type is " + vehType);
}
}
程序运行后结果显示如下:
Car
Your vehicle type is C