public class Goto {
/**
*这个是从java编程思想p149中摘抄下来的,用于理解便签(label),这个虽然提到的是infamous goto 但是只要讲的则是label的使用
*在java中虽然goto作为了保留词,但是java并没有使用goto,而是利用了break和continue作出类似于跳转的效果~
*这个例子对于加深对label的使用还是蛮有用的~
*/
public static void main(String[] args) {
int i=0;
outer ://can't have statements here 这里定义标签名为outer的外层便签
while(true){
System.out.println("Outer while loop");
while(true){//嵌套了另外的一个循环
i++;
System.out.println("i = "+i);
if(i==1){
System.out.println("continue");
continue;//这个的continue是针对当前的循环
}
if(i==3){
System.out.println("continue outer");
continue outer;//这里的continue则是针对外层的那个便签的循环,重新从外边开始
}
if(i==5){
System.out.println("break");
break;//这个中断的是当前的循环
}
if(i==7){
System.out.println("break outer");
break outer;//这个中断的是便签outer这个循环
}
}
}
}
/*
Outer while loop
i = 1
continue
i = 2
i = 3
continue outer
Outer while loop
i = 4
i = 5
break
Outer while loop
i = 6
i = 7
break outer
*/
/**
* 1、A plain continue goes to the top of the innermost loop and continues.(continue会到内部循环的开始,并执行下一步骤)
* 2、A labeled continue goes to the label and reenters the loop right after that label(便签级别的continue会回到便签定义的那层循环,并执行下一个步骤)
* 3、A break "drop out of the bottom " of the loop(break 是从循环的底部跳出,遇到是跳出当前的循环)
* 4、A labeled break drops out of the bottom of the end of the loop denoted by the label(便签级别的break,则是跳出当前被标签化的循环体)
*
* It's important to remember that the only reason to user labels in java is when you hava nested loops and you want to break or continue through more than one nested level
* (要记得在java中使用标签的唯一原因是当你使用嵌套循环的时候,并且你想break 或 continue 多个嵌套的的循环)
*/
}