break语句有两种形式,未标记的和标记的break。在下面的示例中,您将第一个示例视为未标记break。这种类型的break语句将终止内部循环,如for,while和do-while循环。
在第二个示例中,您将看到标记为的break。我们有两个循环,无限循环while和内部for循环。使用标记,break我们可以终止最外面的循环。在for循环中,当值y等于时5,它将break到达start:标签,标签将使程序继续执行至while循环后的行。
package org.nhooo.example.lang; public class BreakDemo { public static void main(String[] args) { int[] numbers = {5, 3, 6, 9, 8, 7, 4, 2, 1, 10}; int index; boolean found = false; int search = 7; for (index = 0; index < numbers.length; index++) { if (numbers[index] == search) { found = true; break; } } if (found) { System.out.println(search + " found at index " + index); } else { System.out.println(search + " was not found."); } start: while (true) { for (int y = 0; y < 10; y++) { System.out.print("y = " + y + "; "); if (y == 5) { System.out.println(""); break start; } } } } }