Java Break语句示例

时间:2020-02-23 14:34:57  来源:igfitidea点击:

Break语句是我们经常使用的不同控制语句之一。
如果在循环中找到Break语句,它将退出循环并执行循环后的语句。

让我们看一下非常简单的例子:

Java Break语句示例

我们要搜索数组中的元素,如果找到元素,则退出循环。

package org.igi.theitroad;
 
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");
	}
 
}

带标记的break语句:

如果你想要中断带标记的for循环时,则使用带标记的break语句。

例如:

我们希望在二维数组中找到一个元素。
在阵列中获取元素后,退出外循环。

package org.igi.theitroad;
 
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");
	}
 
}

我们还可以在Switch Case中使用Break语句。
一旦满足case的条件,我们将退出switch结构。
例如:

package org.igi.theitroad;
 
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);
	}
 
}