Loading...
  所在位置:论坛首页 -> 计算机科学与技术 -> 程序设计 -> Java:Break跳出循环
回复

Java:Break跳出循环

作者:ade 时间:2006-5-31 20:59:07 收藏 编辑

我想很多人没有这样用过break语句,可能有点goto的意思,但是有时候真的很有用。
A break statement is used to exit the current loop or other flow control structure. The program execution is sent to the next statement following the control structure. By default, a break statement inside a nested loop will exit only the current loop, not the entire loop structure. You can add a label after a break statement to break out of a specified labeled block of code.

Example: Breaking Out of an Outer Loop

In this example, two for loops are used to search a 2-D array of data for a negative value. If a negative value is found, its location is noted and the loop exits. We want to exit both the inner and outer loops if a negative value is found. To do this, we label the outer for loop "outer" and use a labeled break statement. If a simple break statement had been used (without the label) only the inner loop would have been exited. The outer loop would continue normally.

    outer: for(int i=0; i<3; ++i) {
for(int j=0; j<3; ++j) {
System.out.println("i= " + i + " j= " + j);
if (data[i][j] < 0.0) {
System.out.println("negative value at" +
" [" + i + "][" + j + "]");
break outer;
}
}

Output—
i=0 j=0
i=0 j=1
i=0 j=2
i=1 j=0
negative value at [1][0]
第2楼 ade
编辑 删除 引用
continue也是这样用的。
回复时间:2006-5-31 21:06:37
第3楼 ade
编辑 删除 引用

翻译一下
break表达式是用来跳出当前循环或者其他流程的(控制结构),执行这条语句后,程序将运行控制结构后面的语句,子循环的break语句缺省只跳出当前子循环而不是整个循环结构。但是你可以在需要跳出的循环处加一个标签(label),然后break之后添加上这个标签就可以跳出指定的代码模块。

例子::跳出外层循环
下面的我就不翻译了,看不明白的话,看代码和结果就明白了
In this example, two for loops are used to search a 2-D array of data for a negative value. If a negative value is found, its location is noted and the loop exits. We want to exit both the inner and outer loops if a negative value is found. To do this, we label the outer for loop "outer" and use a labeled break statement. If a simple break statement had been used (without the label) only the inner loop would have been exited. The outer loop would continue normally.

    outer: for(int i=0; i<3; ++i) {
for(int j=0; j<3; ++j) {
System.out.println("i= " + i + " j= " + j);
if (data[i][j] < 0.0) {
System.out.println("negative value at" +
" [" + i + "][" + j + "]");
break outer;
}
}

输出结果—
i=0 j=0
i=0 j=1
i=0 j=2
i=1 j=0
negative value at [1][0]
回复时间:2006-10-13 16:35:26
第4楼 Jng
编辑 删除 引用

受教了,谢谢

回复时间:2010-11-14 22:44:53
高级回复

操作选项: 评分 加精 解精 奖惩 设专题 设公告 解公告 固顶 总固顶 解固顶 结帖 解结帖 锁帖 解锁 移帖 删帖
  首页
Copyright 2006-2012 HistoryCreator.com Powered By: BBSGood 5
吉ICP备06005902号