在 Java 循环中中断、继续和标签
以下示例展示了 for 语句之前的标签“first”、“second”,并使用 break/continue 控件跳转到该标签。请参阅以下示例。
示例
public class Tester { public static void main(String args[]) { first: for (int i = 0; i < 3; i++) { for (int j = 0; j< 3; j++){ if(i == 1){ continue first; } System.out.print(" [i = " + i + ", j = " + j + "] "); } } System.out.println(); second: for (int i = 0; i < 3; i++) { for (int j = 0; j< 3; j++){ if(i == 1){ break second; } System.out.print(" [i = " + i + ", j = " + j + "] "); } } } }
first 是最外层 for 循环的标签,continue first 使得循环在 i = 1 时跳过 print 语句;
second 是最外层 for 循环的标签,continue second 使得循环中断。
广告