TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
众所周知,在java中,如果想跳出for循环,一般情况下有两种方法:break和continue。
break是跳出当前for循环,如下面代码所示:- public class RecTest {
-
- /**
- * @param args
- */
- public static void main(String[] args) {
- for(int i=0; i< 10; i++){
- if(i==5){
- break;
- }
- System.out.print(i+" ");
- }
- }
- }
复制代码
输出:0 1 2 3 4
也就是说,break会跳出(终止)当前循环。continue是跳出当前循环,开始下一循环,如下所示:- public class RecTest {
-
- /**
- * @param args
- */
- public static void main(String[] args) {
- for (int i = 0; i < 10; i++) {
- if (i == 5) {
- continue;
- }
- System.out.print(i+" ");
- }
- }
- }
复制代码 输出:0 1 2 3 4 6 7 8 9
以上两种方法没有办法跳出多层循环,如果需要从多层循环跳出,则需要使用标签,定义一个标签label,
然后在需要跳出的地方,用break label就行了,代码如下: - public class RecTest {
-
- /**
- * @param args
- */
- public static void main(String[] args) {
-
- loop: for (int i = 0; i < 10; i++) {
- for (int j = 0; j < 10; j++) {
- for (int k = 0; k < 10; k++) {
- for (int h = 0; h < 10; h++) {
- if (h == 6) {
- break loop;
- }
- System.out.print(h);
- }
- }
- }
- }
- System.out.println("
- I"m here!");
- }
- }
复制代码 输出:
012345
I"m here! |
|