1、break用法
1.1 在switch case代码块中终止代码序列。
1.2在循环体中跳出其所在的循环层。
1.3与lable一起使用,类goto用法,注意lable所在的位置必须在。
注意:a.跳出到lable处后,不会再继续执行下面的循环体,
b.lable必须在包含break的代码块中定义,否则编译不通过。
class Test {
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; // exit both loops
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.
// This program contains an error.
class Test {
public static void main(String args[]) {
one: for (int i = 0; i < 3; i++) {
System.out.print("Pass " + i + ": ");
}
for (int j = 0; j < 100; j++) {
if (j == 10)
break one; // WRONG
System.out.print(j + " ");
}
}
}
2、continue的用法
2.1结束本次循环,继续下次循环。
2.2结合lable一起使用,从lable处继续执行。
class Test {
public static void main(String args[]) {
// 九九乘法表
outer: for (int i = 1; i < 10; i++) {
for (int j = 1; j < 10; j++) {
if (j > i) {
System.out.println();
continue outer;
}
System.out.print(i + "*" + j + " ");
}
}
System.out.println();
}
}
3、return的用法
3.1在有返回值的方法中,返回方法指定类型的值。
3.2在void方法中,可以使用return结束方法。
3.3单独在方法中间使用return会导致编译错误,可以将其放在判断语句中。