java中break和continue可以跳出指定循環,break和continue之后不加任何循環名則默認跳出其所在的循環,在其后加指定循環名,則可以跳出該指定循環(指定循環一般為循環嵌套的外循環)。但是sonar給出的建議盡量不要這樣使用,說不符合通適規范,並給出了規范的建議。不過有些情況下規范化的寫法實現起來判斷條件就略顯復雜。
Labels are not commonly used in Java, and many developers do not understand how they work. Moreover, their usage makes the control flow harder to follow, which reduces the code's readability.
Noncompliant Code Example
int matrix[][] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; outer: for (int row = 0; row < matrix.length; row++) { // Non-Compliant for (int col = 0; col < matrix[row].length; col++) { if (col == row) { continue outer; } System.out.println(matrix[row][col]); // Prints the elements under the diagonal, i.e. 4, 7 and 8 } }
Compliant Solution
for (int row = 1; row < matrix.length; row++) { // Compliant for (int col = 0; col < row; col++) { System.out.println(matrix[row][col]); // Also prints 4, 7 and 8 } }