2013-09-24 86 views
0

我有這種方法,確定在給定的行和列的棋盤上的正方形是否受列1到列1中的任何皇后的攻擊。但二繼續板得到一個異常錯誤[行列+ Y] [Y] == QUEEN搜索2維數組。

private boolean isUnderAttack(int row, int column) 
    { 
      for (int y=0; y<column; y++) 
      { 
      if (board[row][y] == QUEEN || // possible horizontal attack 
      board[row-column+y][y] == QUEEN || // diagonal NW 
      board[row+column-y][y] == QUEEN)  // diagonal SW 

      return true; 
      } 

      return false; 
    } 
+1

有什麼異常?的ArrayIndexOutOfBounds?你應該提供更多的信息,但問題是(很可能)很清楚。從例外的指數中,你應該能夠弄清楚。 – NeplatnyUdaj

+0

在NW測試中,如果所討論的方格有低行,低y和高列值,則最終會得到負指數。 –

回答

1

收費attetion到:

row + column - y 

此操作可以返回比較小的數0

你的類應該是這樣的:

import java.util.Arrays; 

public class Board { 

private final int[][] board; 
private final int dimention; 

public static void main(final String[] args) { 
    final Board p = new Board(6); 
    for (final int[] i : p.board) { 
     System.out.println(Arrays.toString(i)); 
    } 
    p.isUnderAttack(2, 3); 
    System.out.println("\n\n"); 
    for (final int[] i : p.board) { 
     System.out.println(Arrays.toString(i)); 
    } 

} 

public Board(final int dimention) { 
    this.dimention = dimention; 
    this.board = new int[dimention][dimention]; 
} 

private void isUnderAttack(final int row, final int column) { 

    for (int y = 0; y < this.dimention; y++) { 
     this.board[y][row] = 1; // possible horizontal attack 
     this.board[column][y] = 2; // possible vertical attack 
    } 
    int staringRow = column - row; 
    int y = 0; 
    do { 
     this.board[staringRow][y] = 3; // diagonal SW 
    } while ((++staringRow < this.dimention) && (++y < this.dimention)); 

    int staringCol = column + row; 
    int x = 0; 
    do { 
     this.board[x][staringCol] = 4; // diagonal NW 

    } while ((++x < this.dimention) && (--staringCol < this.dimention)); 
} 

} 

這是此測試的輸出:

[0, 0, 0, 0, 0, 0] 
[0, 0, 0, 0, 0, 0] 
[0, 0, 0, 0, 0, 0] 
[0, 0, 0, 0, 0, 0] 
[0, 0, 0, 0, 0, 0] 
[0, 0, 0, 0, 0, 0] 



[0, 0, 1, 0, 0, 4] 
[3, 0, 1, 0, 4, 0] 
[0, 3, 1, 4, 0, 0] 
[2, 2, 4, 2, 2, 2] 
[0, 4, 1, 3, 0, 0] 
[4, 0, 1, 0, 3, 0] 
+0

謝謝...不是我在找什麼。但給了我一個主意 – user1896464