我有一個二維數組,並需要做一個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語句以某種方式終止了外部循環和內部循環。
'break'只有退出內部循環 - 它看起來像現在將是學習如何使用調試器的好時機。 – assylias
你能提供一個'int [] [] board'的例子嗎? 'break'語句可能會將您從double for循環中取出。你需要考慮另一種方式。例如,你可以嘗試把第二個'for循環'放在'public int getCountForRow(int [] row)'方法 – Al1