轉自:http://lihengzkj.iteye.com/blog/1090034
以前不知道在循環中可以使用標簽。最近遇到后,舉得還是有其獨特的用處的。我這么說的意思是說標簽在循環中可以改變循環執行的流程。而這種改變不是我們以前單獨使用break或者是continue能夠達到的。下面還是看看實例吧。
- outer1:
- for(int i =0;i<4;i++){
- System.out.println("begin to itrate. "+i);
- for(int j =0;j<2;j++){
- if(i==2){
- continue outer1;
- // break;
- }
- System.out.println("now the value of j is:"+j);
- }
- System.out.println("******************");
- }
執行的結果是:
begin to itrate. 0
now the value of j is:0
now the value of j is:1
******************
begin to itrate. 1
now the value of j is:0
now the value of j is:1
******************
begin to itrate. 2
begin to itrate. 3
now the value of j is:0
now the value of j is:1
******************
注:當i=2的時候,continue outer1 使程序回到了outer1最開始循環的位置,開始下一次循環,這個時候執行的循環是i=3而不是重新從i=0開始。同時當使用continue outer1跳出內層循環的時候,外層循環后面的語句也不會執行。也就是是在begin to itrate. 2后面不會出現一串*號了。
對比:
- outer1:
- for(int i =0;i<4;i++){
- System.out.println("begin to itrate. "+i);
- for(int j =0;j<2;j++){
- if(i==2){
- // continue outer1;
- break;
- }
- System.out.println("now the value of j is:"+j);
- }
- System.out.println("******************");
- }
注:我們直接使用break的話,只是直接跳出內層循環。結果其實就可以看出區別來:
begin to itrate. 0
now the value of j is:0
now the value of j is:1
******************
begin to itrate. 1
now the value of j is:0
now the value of j is:1
******************
begin to itrate. 2
******************
begin to itrate. 3
now the value of j is:0
now the value of j is:1
******************
-----------------------------------------------------------------分割線
我們再來看看break+標簽的效果
- outer2:
- for(int i =0;i<4;i++){
- System.out.println("begin to itrate. "+i);
- for(int j =0;j<2;j++){
- if(i==2){
- break outer2;
- // break;
- }
- System.out.println("now the value of j is:"+j);
- } System.out.println("******************");
- }
結果:
begin to itrate. 0
now the value of j is:0
now the value of j is:1
******************
begin to itrate. 1
now the value of j is:0
now the value of j is:1
******************
begin to itrate. 2
注:從結果就可以看出當i=2的時候,break+標簽 直接把內外層循環一起停掉了。而如果我們單獨使用break的話就起不了這種效果,那樣只是跳出內層循環而已。
最后說一句,Java中的標簽只適合與嵌套循環中使用。