break和continue的用法
2009-03-05 19:05
381 查看
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
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
相关文章推荐
- break,continue,break的用法与区别
- 小tips:JS之break,continue和return这三个语句的用法
- Java 控制语句 break 和 continue 的用法
- for while break continue exit 用法
- Java基础知识2.2-循环嵌套以及break.continue的用法
- C#中return、break、continue的用法
- Java中for循环中执行顺序问题及break, continue用法
- break和continue的用法
- java中 break,continue和return的用法
- break、continue、return的用法
- break与continue的用法及区别
- php中break与continue的区别和用法举例
- Break、continue、return用法(C++)
- continue和break的用法
- C++中break和continue的用法
- Break与Continue用法注意事项
- JavaScript中break、continue、return的用法
- C++ continue 和 break 的用法
- shell-3:while循环中break和continue的用法
- c语言中break和continue的用法和区别