break是我們用于退出循環(huán)的語句之一俏拱。如果在循環(huán)中發(fā)現(xiàn)break坦袍,它將退出循環(huán)并執(zhí)行循環(huán)后面的語句苟蹈。
break:
我們通過一個(gè)示例來理解break葵擎。
假設(shè)我們需要在一個(gè)數(shù)組中查找一個(gè)元素,如果找到該元素互亮,我們則可以使用break退出循環(huán)犁享。
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語句被執(zhí)行余素,退出當(dāng)前循環(huán)
}
}
System.out.println("Executing statments following the loop");
}
}
上面程序運(yùn)行后的結(jié)果顯示如下:
53 is present in the array
Executing statements following the loop
標(biāo)簽的break
break通常只中斷當(dāng)前循環(huán)豹休。假如有多個(gè)循環(huán)嵌套時(shí),你想要退出嵌套在最外的循環(huán)時(shí)桨吊,你可以使用標(biāo)簽的break語句威根。
我們通過一個(gè)示例來理解它。
示例
假設(shè)你想在一個(gè)二維數(shù)組中找到某一元素视乐。 一旦找到數(shù)組中的該元素洛搀,則退出外部循環(huán)。
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被執(zhí)行佑淀,系統(tǒng)將退出outer for循環(huán)
}
}
}
System.out.println("Executing statements following the outer loop");
}
}
程序運(yùn)行后顯示結(jié)果如下:
65 is present in the array
Executing statements following the outer loop
Switch Case:
你也可以在switch case中使用break語句留美。 一旦條件符合,程序?qū)⑼顺鰏witch 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);
}
}
程序運(yùn)行后結(jié)果顯示如下:
Car
Your vehicle type is C