|
JAVA程序员必读:基础篇(3)语言基础
|
|
编译:ZSC/太平洋网络学院
|
|
|
语言基础
3.4.6 分支语句
未标志形式的break语句被用来终止内部的switch、for、while或者do-while。而标志形式的break语句终止一个外部的语句,它是通过在break语句中使用一个标志来实现的。下面的例程BreakWithLabelDemo跟前面的例子有点相似,只不过它是在一个两维数组中搜索一个数值。利用两个嵌套的for循环遍历了整个数组。当数值被找到了,标志形式的break语句就终止标志的search语句,这个search语句是在for循环外部的:
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 = 0;
int j = 0;
boolean foundIt = false;
search:
for ( ; i < arrayOfInts.length;
i++) {
for (j = 0; j < arrayOfInts[i].length;
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");
}
}
}
这个程序的输出为:
Found 12 at 1, 0
这个语法看起来可能有点费解。break语句终止了标志语句,它不能将控制流程转到这个标志处。控制流程迅速将标志(终止的)后面的语句。
[上一页] [下一页]
|