Java-突破内循环

时间:2017-10-11 14:56:54

标签: java if-statement

我有一个2D数组,需要制作一个遍历每一行的for循环,并在整数停止连续增加时找到索引+ 1。例如,如果第一行是{1,2,3,4,9,10,11,20},我的方法应该设置count1 = 4。 break语句用于终止内部循环并继续执行外部循环的下一个序列。

 public static int[][] reshuffle(int[][] board) {
        int count1 =0;
        int count2 =0;
        int count3 =0;
        int count4 =0;
        for(int i=0;i<4;i++) {
            for (int j = 0; j < 14; j++) {
                if (i==0 && board[i][j] + 1 != board[0][j + 1]) {
                    count1 = j+1;
                    break;
                } else if (i==1 && board[i][j] + 1 != board[1][j] + 1) {
                    count2 = j+1;
                    break;
                } else if (i==2 && board[i][j] + 1 != board[2][j] + 1) {
                    count3 = j+1;
                    break;
                } else if (i==3 && board[i][j] + 1 != board[3][j] + 1) {
                    count4 = j+1;
                    break;
                }

            }
        }
}

我的程序将返回count1的正确值,但始终为count2,count3和count4返回0。这向我表明break语句以某种方式终止了外部循环以及内部循环。

2 个答案:

答案 0 :(得分:3)

我认为你有一个逻辑错误,因为i = 3 board[i][j] + 1将等于board[3][j] + 1我认为你的意思是:

public static int[][] reshuffle(int[][] board) {
    int count1 = 0;
    int count2 = 0;
    int count3 = 0;
    int count4 = 0;

    for(int i=0;i<4;i++) {
       for (int j = 0; j < 14; j++) {
           if (i==0 && board[i][j] + 1 != board[0][j + 1]) {
               count1 = j+1;
               break;
           } else if (i==1 && board[i][j] + 1 != board[1][j + 1]) {
               count2 = j+1;
               break;
            } else if (i==2 && board[i][j] + 1 != board[2][j + 1]) {
                count3 = j+1;
                break;
             } else if (i==3 && board[i][j] + 1 != board[3][j + 1]) {
                count4 = j+1;
                break;
             }
        }   
    }
}

答案 1 :(得分:0)

您可以使用标签并打破这些标签,但这是not a good approach

public static int[][] reshuffle(int[][] board) {
        int count1 =0;
        int count2 =0;
        int count3 =0;
        int count4 =0;
        for(int i=0;i<4;i++) {
            level1:
            for (int j = 0; j < 14; j++) {
                if (i==0 && board[i][j] + 1 != board[0][j + 1]) {
                    count1 = j+1;
                    break level1;
                } else if (i==1 && board[i][j] + 1 != board[1][j] + 1) {
                    count2 = j+1;
                    break level1;
                } else if (i==2 && board[i][j] + 1 != board[2][j] + 1) {
                    count3 = j+1;
                    break level1;
                } else if (i==3 && board[i][j] + 1 != board[3][j] + 1) {
                    count4 = j+1;
                    break level1;
                }

            }
        }
}

我建议重构代码以避免内部循环,例如:使用单独的方法。