2017-10-11 113 views
1

我有一个二维数组,并需要做一个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语句以某种方式终止了外部循环和内部循环。

+0

'break'只有退出内部循环 - 它看起来像现在将是学习如何使用调试器的好时机。 – assylias

+0

你能提供一个'int [] [] board'的例子吗? 'break'语句可能会将您从double for循环中取出。你需要考虑另一种方式。例如,你可以尝试把第二个'for循环'放在'public int getCountForRow(int [] row)'方法 – Al1

回答

3

我认为你有一个逻辑错误,因为i = 3board[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; 
      } 
     } 
    } 
} 
+0

打我吧......你是对的。其他三种情况将永远失败。 –

+0

这解决了我的问题。 – user8735495

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; 
       } 

      } 
     } 
} 

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

+0

我认为标签应该出现在两个循环之外。 – notyou