2017-10-11 64 views
2

我有一個2D數組填充連續整數1-52以及四個0。我也創建了一個計數變量並將其設置爲0;我想搜索整個數組,並且對於緊跟在13,26,39或52之後的每個0,增量爲count++Java-在數組中搜索尾隨0

int count =0; 
for(int i=0;i<4;i++) { 
    for(int j=0; j<4;j++) { 
     if((board[i][j]== 13 && board[i][j+1]==0) || (board[i][j]== 26 && board[i][j+1]==0) || (board[i][j]== 39 && board[i][j+1]==0) || (board[i][j]== 52 && board[i][j+1]==0)) { 
      count++; 
     } 
    } 
} 
while(count <4) { 
    move(board); 
} 

我的當前代碼正常運行,並且會按照這些數字遞增計數爲單個零。但是,如果我的四個數字之一緊跟兩個0(三個0的爲increment +=3,四個0的爲+=4),我想增加count+=2

+0

如果''A [1] [n]的== 0''和''A [1 + 1] [0] == 13''例如,這是否計數? –

+0

你確定,你想用數組來做這個嗎?那麼在那種情況下定義一個方法會如何返回這些選定數字的前0個連續0的計數呢? – nullpointer

回答

1

只是要另一種方法來計算零:

int count =0; 
     for(int i=0;i<4;i++) { 
      for(int j=0; j<4;j++) { 
       if((board[i][j]== 13 || board[i][j]== 26 || board[i][j]== 39 || board[i][j]== 52) && board[i][j+1]==0) { 
        count += numberOfZeros(i, j); 
       } 
      } 
     } 
     while(count <4) { 
      move(board); 
     } 
    } 

    public int numberOfZeros(int i, int j){ 

     int aux = 0; 
     for(; j<4;j++) { 
      if(board[i][j] == 0){ 
       aux++; 
      } 
     } 
     return aux; 
    } 

PS:我編輯你的if語句,以使其更清晰

+1

你可能想爲非連續的0設置一個'else {break;}'。 – nullpointer

+0

另外第二個循環應該是''for(int j = 0; j <4 - 1; j ++)''。或者你可能會得到一個''ArrayIndexOutOfBoundsException'' –

+0

@SchiduLuca如果情況是這樣的話,即使在問題中共享的代碼也不會有標記的*代碼正常運行*。雖然我同意這個問題在輸入方面不明確。 – nullpointer

0

您可以使用一個布爾值來檢查您是否是一個計數「連勝「零的:

int count = 0; 
boolean onACountStreak = false; 
for (int i = 0; i < 4; i++) { 
    for (int j = 0; j < 4; j++) { 

     if (board[i][j] == 0) { 
      // Count only if this zero is found in a streak 
      if (onACountStreak) { 
       count++; 
      } 
     } 
     else if (board[i][j] % 13 == 0) { 
      onACountStreak = true; 
     } 
     else { 
      onACountStreak = false; 
     } 
    } 
} 

while (count < 4) { 
    move(board); 
}