2017-10-11 114 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