2013-03-04 54 views
0

我試圖創建一個程序,以特定的方式在網格上排列6張卡,以便沒有卡與相同類型的其他卡(類型爲國王,王后和插孔)相鄰, 。網格是4x4的,但我只能把卡下面的模式中:Java數組 - 相鄰卡

[ ][ ][x][ ] 
[x][x][x][ ] 
[ ][x][x][x] 
[ ][ ][x][ ] 

現在,我的主要問題是,當我的方法嘗試檢查相鄰小區的卡片類型。當它從0,0開始時,它會嘗試檢查[row-1] [column],這顯然不起作用,因爲它轉換爲-1,0。問題是,我不知道如何正確實施。

我很抱歉如果之前詢問過這個問題,因爲我不確定要準確搜索什麼(或者如何正確命名這個問題)。

private boolean bordersCard(int row, int column, char cardChar) 
    { 
     Candidate center = board[row][column]; 
     Candidate top; 
     Candidate bottom; 
     Candidate left; 
     Candidate right; 

     if (board[row-1][column] != null){ 
      top = board[row+1][column]; 
     } 
     else 
     { 
      top = new Candidate('?', 0); 
     } 

     if (board[row+1][column] != null){ 
      bottom = board[row+1][column]; 
     } 
     else 
     { 
      bottom = new Candidate('?', 0); 
     } 

     if (board[row][column-1] != null){ 
      left = board[row][column-1]; 
     } 
     else 
     { 
      left = new Candidate('?', 0); 
     } 
     if (board[row][column+1] != null){ 
      right = board[row][column+1]; 
     } 
     else 
     { 
      right = new Candidate('?', 0); 
     } 

     if ((center.getCardChar() == top.getCardChar()) || (center.getCardChar() == bottom.getCardChar()) || 
     (center.getCardChar() == left.getCardChar()) || (center.getCardChar() == right.getCardChar())){ 
      return false; 
     } 
     return true; 
    } 

回答

0

您必須添加if圍欄,以防止無效檢查:

if (row > 0 && board[row-1][column] != null){ 
    top = board[row+1][column]; 
} 
+0

謝謝,成功了! – Anubis 2013-03-04 19:11:24

0

正如你已經確定,檢查[-1] [0]不起作用。但是你不需要檢查那個不存在的插槽。只要確保你不會跑掉陣列的開始或結束。此外,請確保您的if內爲您的病情執行相同的數學運算:

if ((row - 1) >= 0 && (row - 1) < board.length && board[row-1][column] != null){ 
    top = board[row-1][column]; // Use -1 to match condition. 
} 
0

如果任何一個指標都出界將它們分配爲NULL。在Candidate中創建一個方法isSameType(Candidate other);

isSameType(Candidate other) 
{ 
    if(other == null) 
    return false; 
    else 
    retrun getCardChar() == other.getCardChar(); 
} 

改變你如果到:

if(center.isSameType(top) || center.isSameType(bottom) || ...) 
{ 
    return false; 
}