break和continue的用法

来源:互联网 发布:法国电影 知乎 编辑:程序博客网 时间:2024/05/18 03:52

1.使用break退出一层循环
public static void main(String args[])
{
 int i=0;
 while(i<100)
 { 
  if(i==10) break;
  System.out.println("i="+i);
  i++;
 }
}

Attention:当break用在一组嵌套循环时,将仅跳出最里面的循环。

2.使用break退出多层循环
public static void main(String args[])
{
 outer:
 for(int i=0; i<3; i++)
 {
  System.out.print("Pass "+i+":");
  for(int j=0; j<100; j++)
  {
   if(j==10)
    break outer;
   System.out.print(j+" ");
  }
  System.out.println("This will not print");
 }
 System.out.println("loops complete.");
}

程序的输出:
Pass 0: 0 1 2 3 4 5 6 7 8 9 loops complete.

continue的使用
1.在一层循环中的使用
public static void main(String args[])
{
 for(int i=0; i<10; i++)
 {
  System.out.print(i+" ");
  if(i%2==0)
   continue;
  System.out.println("");
 }
}

输出结果:
0 1
2 3
4 5
6 7
8 9

2.在多层循环中使用
public static void main(String args[])
{
 outer:
 for(int i=0; i<10; i++)
  for(int j=0; j<10; j++)
  {
   if(j>i)
   {
    System.out.println();
    continue outer;
   }
   System.out.print(" "+(i*j));
  }
  
 System.out.println();
}

0
0 1
0 2 4
0 3 6 9
0 4 8 12 16
0 5 10 15 20 25
0 6 12 18 24 30 36
0 7 14 21 28 35 42 49
0 8 16 24 32 40 48 56 64
0 9 18 27 36 45 54 63 72 81

原创粉丝点击