java中的break 语句总结

发表于: java/j2ee | 作者: darkmi | 日期: 2011/03/09 08:00
标签: break, CoreJava
字号:

在java中,break语句有两种形式:无标签和有标签。无标签的break语句用来跳出单层switch、for、while、or do-while 循环,而有标签的break语句则用来跳出嵌套的switch、for、while、or do-while语句。

以下是一个无标签示例:

package com.darkmi.basic;

public class BreakDemo {

	public static void main(String[] args) {

		int[] arrayOfInts = { 32, 87, 3, 589, 12, 1076, 2000, 8, 622, 127 };
		int searchfor = 12;

		int i;
		boolean foundIt = false;

		for (i = 0; i < arrayOfInts.length; i++) {
			if (arrayOfInts[i] == searchfor) {
				foundIt = true;
				break;
			}
		}

		if (foundIt) {
			System.out.println("Found " + searchfor + " at index " + i);
		} else {
			System.out.println(searchfor + " not in the array");
		}
	}

}

示例程序在一个整型数组中搜索数字12。当该值被找到后,break语句马上终止了for循环,程序的执行流程开始进入打印操作。该示例程序的输出如下:

Found 12 at index 4

无标签的break语句只能终止 switch, for, while, or do-while 语句的内层循环,而有标签的break语句则可以终止外层循环。这对于嵌套的for循环来说,非常有意义。

以下是一个有标签示例:

package com.darkmi.basic;

public class BreakWithLabelDemo {
	public static void main(String[] args) {

		int[][] arrayOfInts = { { 32, 87, 3, 589 }, { 12, 1076, 2000, 8 },{ 622, 127, 77, 955 } };
		int searchfor = 12;

		int i;
		int j = 0;
		boolean foundIt = false;

		search: for (i = 0; i < arrayOfInts.length; i++) {
			for (j = 0; j < arrayOfInts[i].length; j++) {
				System.out.println("正在检索arrayOfInts[" + i + "][" + j + "] --> "
						+ arrayOfInts[i][j]);
				if (arrayOfInts[i][j] == searchfor) {
					foundIt = true;
					break search;
				}
			}
		}

		if (foundIt) {
			System.out.println("Found " + searchfor + " at " + i + ", " + j);
		} else {
			System.out.println(searchfor + " not in the array");
		}
	}

}

输出:

正在检索arrayOfInts[0][0] --> 32
正在检索arrayOfInts[0][1] --> 87
正在检索arrayOfInts[0][2] --> 3
正在检索arrayOfInts[0][3] --> 589
正在检索arrayOfInts[1][0] --> 12
Found 12 at 1, 0

**break search;**语句直接终止了标签语句(标签后边的第一条语句,本处则指嵌套for循环),而不是将程序的执行流程转交给标签语句,程序执行流程直接进入紧邻标签语句的下一条语句。

文章来源:http://download.oracle.com/branch.html

切换主题切换主题
返回顶部