java循环控制语句loop使用

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
  }
}
posted @ 2019-10-30 09:36  斑马森林  阅读(5871)  评论(0编辑  收藏  举报