Java break语句,标签
时间:2020-02-23 14:36:23 来源:igfitidea点击:
Java break语句用于终止处理之间的循环。
我们使用break
reserve关键字来打破Java程序中的循环。
Java break
break语句有两种形式-未标记和标记。
通常,break语句用于根据某些条件终止循环,例如,如果到达exit命令,则中断处理。
无标签的break语句用于终止包含它的循环,并且可以与switch,for,while和do-while循环一起使用。
java break示例
这是显示for循环,while循环和do-while循环中java break语句用法的示例。
package com.theitroad.util; package com.theitroad.util; public class JavaBreak { public static void main(String[] args) { String[] arr = { "A", "E", "I", "O", "U" }; //find O in the array using for loop for (int len = 0; len < arr.length; len++) { if (arr[len].equals("O")) { System.out.println("Array contains 'O' at index: " + len); //break the loop as we found what we are looking for break; } } //use of break in while loop int len = 0; while (len < arr.length) { if (arr[len].equals("E")) { System.out.println("Array contains 'E' at index: " + len); //break the while loop as we found what we are looking for break; } len++; } len = 0; //use of break in do-while loop do { if (arr[len].equals("U")) { System.out.println("Array contains 'U' at index: " + len); //break the while loop as we found what we are looking for break; } len++; } while (len < arr.length); } }
请注意,如果我们删除break语句,则程序输出将不会有任何差异。
对于此示例中的小迭代,没有太大的性能优势。
但是,如果迭代器大小很大,则可以节省大量处理时间。
Java中断标签
标记为break的语句用于终止外部循环,应标记该循环才能正常工作。
这是显示java break标签语句用法的示例。
package com.theitroad.util; public class JavaBreakLabel { public static void main(String[] args) { int[][] arr = { { 1, 2 }, { 3, 4 }, { 9, 10 }, { 11, 12 } }; boolean found = false; int row = 0; int col = 0; //find index of first int greater than 10 searchint: for (row = 0; row < arr.length; row++) { for (col = 0; col < arr[row].length; col++) { if (arr[row][col] > 10) { found = true; //using break label to terminate outer statements break searchint; } } } if (found) System.out.println("First int greater than 10 is found at index: [" + row + "," + col + "]"); } }