个性化阅读
专注于IT技术分析

Java break语句

本文概要

当一个循环内遇到一个break语句,循环立即终止,程序控制继续在该循环之后的下一条语句。

Java的突破是用来中断循环或switch语句。它打破了计划的在规定条件下的电流。在内部循环的情况下,它打破了只有内环。

我们可以使用Java break语句在所有类型的循环如for循环,while循环和do-while循环。

句法:

jump-statement;  
break;

Java的break语句与循环

例:

//Java Program to demonstrate the use of break statement  
//inside the for loop.
public class BreakExample {
public static void main(String[] args) {
    //using for loop
    for(int i=1;i<=10;i++){
    	if(i==5){
    	    //breaking the loop
    		break;
    	}
    	System.out.println(i);
    }
}
}

输出:

1
2
3
4

Java的break语句

它打破了只有在使用打破了循环内声明内环。

例:

//Java Program to illustrate the use of break statement  
//inside an inner loop 
public class BreakExample2 {
public static void main(String[] args) {
            //outer loop 
	        for(int i=1;i<=3;i++){  
	                //inner loop
	                for(int j=1;j<=3;j++){  
	                    if(i==2&&j==2){  
	                        //using break statement inside the inner loop
	                        break;  
	                    }  
	                    System.out.println(i+" "+j);  
	                }  
	        }  
}
}

输出:

1 1
1 2
1 3
2 1
3 1
3 2
3 3

Java的break语句标有对应循环

我们可以用break语句带有标签。因为JDK 1.5此功能介绍。因此,我们可以在Java中打破任何环现在无论是外循环或内。

例:

//Java Program to illustrate the use of continue statement
//with label inside an inner loop to break outer loop
public class BreakExample3 {
public static void main(String[] args) {
            aa:
	        for(int i=1;i<=3;i++){  
	                bb:
	                for(int j=1;j<=3;j++){  
	                    if(i==2&&j==2){  
	                        //using break statement with label
	                        break aa;  
	                    }  
	                    System.out.println(i+" "+j);  
	                }  
	        }  
}
}

输出:

1 1
1 2
1 3
2 1

在while循环的Java break语句

例:

//Java Program to demonstrate the use of break statement
//inside the while loop.
public class BreakWhileExample {
public static void main(String[] args) {
    //while loop
    int i=1;
    while(i<=10){
        if(i==5){
    	    //using break statement
            i++;
    		break;//it will break the loop
    	}
    	System.out.println(i);
        i++;
    }
}
}

输出:

1
2
3
4

Java的break语句do-while循环

例:

//Java Program to demonstrate the use of break statement
//inside the Java do-while loop.
public class BreakDoWhileExample {
public static void main(String[] args) {
    //declaring variable
    int i=1;
    //do-while loop
    do{
        if(i==5){
    	   //using break statement
           i++;
    	   break;//it will break the loop
    	}
    	System.out.println(i);
        i++;
    }while(i<=10);
}
}

输出:

1
2
3
4

Java的break语句与开关

要了解与switch语句突破的例子,请点击这里查看:Java的switch语句。

赞(0)
未经允许不得转载:srcmini » Java break语句

评论 抢沙发

评论前必须登录!