2013-03-04 60 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; 
}