这是一个解决此问题的完整示例。请参阅代码中的注释了解更多详情:
public class Boolean_Array
{
private static final int SIZE = 8;
public static void main(String[] args)
{
// create the boolean array
boolean [][] boolArr = new boolean [SIZE][SIZE];
// 1. Set the row, col of the true
int row = 3;
int col = 5;
// 2. Make the vertical, horizontal and diagonals true
for (int i = 0; i < SIZE; i++)
{
// Do the vertical and horizontal
boolArr[row][i] = true;
boolArr[i][col] = true;
// Do the diagonals
setDiagonol(boolArr, row - i, col - i, i); // up and to the left
setDiagonol(boolArr, row - i, col + i, i); // up and to the right
setDiagonol(boolArr, row + i, col - i, i); // down and to the left
setDiagonol(boolArr, row + i, col + i, i); // down and to the right
}
print(boolArr);
}
private static void setDiagonol (boolean [][] boolArr, int row, int col, int i)
{
try
{
boolArr[row][col] = true;
}
catch (java.lang.ArrayIndexOutOfBoundsException aioobe)
{
// catching for convenience so we don't have to check the bounds
}
}
private static void print (boolean [][] boolArr)
{
for (int i = 0; i < SIZE; i++)
{
for (int j = 0; j < SIZE; j++)
{
System.out.print(boolArr[i][j] == true ? "X " : "0 ");
}
System.out.println();
}
}
}
输出:
0 X 0 0 0 X 0 0
0 0 X 0 0 X 0 0
0 0 0 X 0 X 0 X
0 0 0 0 X X X 0
X X X X X X X X
0 0 0 0 X X X 0
0 0 0 X 0 X 0 X
0 0 X 0 0 X 0 0
在哪里代码将被放置。它是在第三循环中还是在第二循环中的if语句中?因为如果代码位于第三个循环 –
之内,则此代码无效。 – Drone6251