Java中的continue语句——通过示例学习Java编程(12)

作者:CHAITANYA SINGH

来源:https://www.koofun.com//pro/kfpostsdetail?kfpostsid=23

continue语句主要是用在循环代码块中。当程序在循环代码块中执行到continue语句时,程序会跳过continue后面的所有的循环代码块中的语句,直接跳到循环代码块的第一条语句。当我们在一个循环代码块中执行到某条语句后,如果我们不想继续执行后面的语句,而是想立即回到循环代码块的第一条语句,重新开始循环,这时候我们就可以在这里加上一个continue语句。

语法:continue单词后面跟着分号,如下:

1
continue ;

示例:for循环内部的continue语句

1
2
3
4
5
6
7
8
9
10
11
12
13
public  class  ContinueExample {
 
    public  static  void  main(String args[]){
            for  ( int  j= 0 ; j<= 6 ; j++){
              if  (j== 4 )
              {
           continue ;
     }
 
              System.out.print(j+ " " );
            }
    }
}

输出:

1
0  1  2  3  5  6

您可能已经注意到,输出中缺少值4,为什么?这是因为当变量j的值为4的时候,程序会遇到一个continue语句,这意味着程序会跳过continue语句后面的打印语句,直接回到for循环的开始的地方,重新开始下一次的循环,这样就导致程序的输出结果里面没有4。

continue语句流程图

Java中的continue语句——通过示例学习Java编程(12)_第1张图片

示例:continue在while循环中的使用

和上面的例子类似,我们在while循环中,我们把变量counter的值从10递减(counter--)到0。但是,当counter的值为7是,程序执行到continue语句,就不再执行后面的语句,而是回到while循环的开始的语句,重新开始循环。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public  class  ContinueExample2 {
 
    public  static  void  main(String args[]){
            int  counter= 10 ;
            while  (counter >= 0 ){
              if  (counter== 7 )
              {
            counter--;
            continue ;
                }
              System.out.print(counter+ " " );
              counter--;
            }
    }
}

输出:

1
10  9  8  6  5  4  3  2  1  010  9  8  6  5  4  3  2  1  0

示例:continue在do-while循环中的使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public  class  ContinueExample3 {
 
    public  static  void  main(String args[]){
         int  j= 0 ;
         do
         {
               if  (j== 7 )
               {
             j++;
             continue ;
               }
               System.out.print(j+  " " );
                j++;
           } while (j< 10 );          
        }
}

输出:

1
0  1  2  3  4  5  6  8  9

 

转载于:https://www.cnblogs.com/lea1941/p/10873782.html

你可能感兴趣的:(Java中的continue语句——通过示例学习Java编程(12))