Break语句是我们经常使用的不同控制语句之一。如果在循环中找到break语句,它将退出循环并执行循环后面的语句。
Break
让我们举一个非常简单的例子:
您想在数组中搜索元素,如果找到元素,则退出循环。
package org.arpit.java2blog; public class BreakStatementExample { public static void main(String[] args) { BreakStatementExample bse=new BreakStatementExample(); 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 statement is encounter, control will exit current loop now } } System.out.println("Executing statments following the loop"); } }
当你运行上面的程序时,你会得到下面的输出:
53 is present in the array Executing statments following the loop
当您想要中断标记的 for 循环时,使用标记的 break 语句。
例如:
您想在二维数组中找到一个元素。获得数组中的元素后,退出外循环。
package org.arpit.java2blog; public class LabeledBreakStatementExample { public static void main(String[] args) { LabeledBreakStatementExample bse = new LabeledBreakStatementExample(); 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 statement is encountered, control will exit // outer loop now } } } System.out.println("Executing statements following the outer loop"); } }
65 is present in the array Executing statements following the outer loop
开关盒:
您还可以在 switch case 中使用 break 语句。一旦满足 case 条件,您将退出 switch case。 例如:
package org.arpit.java2blog; public class SwitchCaseExample { 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
这就是Java break 语句示例的全部内容。
原文链接:https://codingdict.com/