Java开发中的break的三种用法
1、汇总:在Java中,或者在编程中(其实C语言和其它语言也有大致雷同用法),break有三种用法,其中的两种非常常用,就是switch语言的break终止和循环语句中(for,While,do While)的break跳出循环。第三种不常用,就是做为“goto“语句跳到指定位置。先来说说常用的两种:
2、Switch中的break,跳出语句,代码如下:public static void main(String[] args) { int i = 5; switch(i){ case 1: System.out.println("this is "+1); break;//break根據業務需求來決定是否添加 case 2: System.out.println("This is "+ 2); break; case 3: System.out.println("This is "+ 3); break; case 4: System.out.println("This is "+ 4); break; case 5: System.out.println("This is "+ 5); break; default: System.out.println("This is "); } }

4、break在循环中的使用,这里用双for循环为例;代码如下:public static void main(String[] args) { int i = 10; for(;i<=15;i++){ for(int j=0;j<=i;j++){ System.out.print(j+" "); if(j==3){ break; } } System.out.println("this is i:"+i); } }


7、总结:break 设计初衷并不是提供一种正常的循环终止的方法。循环的条件语句是专门用来终止循环的。只有在某类特殊的情况下,或者业务需要,才用break 语句来取消一个循环。