我必須編寫設置8x8矩陣棋盤的代碼,然後詢問用戶他們想要放置皇后的行和列。然後我必須在女王可以移動的每個方格上放一個*。女王可以移動的行和列上的*號並不難,但我無法正確標記女王可以移動的對角線。這是迄今爲止我已經寫了嘗試並找到對角線代碼:找到正方形2D陣列中任意一個隨機點的對角線
char[][] chessboard = new char[8][8];
System.out.print("What row do you want to place the queen on? ");
int row = console.nextInt();
System.out.print("What column do you want to place the queen on? ");
int column = console.nextInt();
char queen = 'Q';
chessboard[row - 1][column - 1] = queen;
// column and rows
for (int i = 0; i < chessboard.length; i++) {
for (int j = 0; j < chessboard[0].length; j++) {
if ((i == 2 || j == 6) && chessboard[i][j] != queen) {
chessboard[i][j] = '*';
}
}
}
if ((row - 1) != 0) {
// left diagonal
for (int i = 0; i < row; i++) {
for (int j = (column - 1 - (row - 1)); ((column - 1) - (row - 1)) <= j && j < column; j++) {
if (chessboard[i][j] != queen) {
chessboard[i][j] = '*';
}
}
}
for (int i = (row - 1) + (8 - (column)); i >= row - 1; i--) {
for (int j = 7; j >= (column - 1); j--) {
if (chessboard[i][j] != queen) {
chessboard[i][j] = '*';
}
}
}
// right diagonal
for (int i = 7; i >= row - 1; i--) {
for (int j = (column - 1 - (row - 1)); 0 <= j && j < column; j--) {
if (chessboard[i][j] != queen) {
chessboard[i][j] = '*';
}
}
}
}
for (int i = 0; i < chessboard.length; i++) {
for (int j = 0; j < chessboard[0].length; j++) {
System.out.print(chessboard[i][j] + " ");
}
System.out.println();
}
}
當我把實驗值,例如第3行和列7,我得到一個非常混亂的輸出。對於上面的數字,我得到:
[][][][] * * * []
[][][][] * * * []
* * * * * * Q *
* * * * * [] * *
* * * * * [] * []
* * * * * [] * []
* * * * * [] * []
* * * * * [] * []
有人能告訴我我哪裏出錯了嗎? *這是一個家庭作業問題,所以請只在答案中提供代碼。謝謝!
什麼的方括號表示您的輸出? – ManoDestra
@ManoDestra他們應該是空矩陣插槽。這就是他們在我的電腦上出現在Intellij-idea中的方式。 – ch1maera
如果是我,我只需循環遍歷棋盤上的每個方格,然後測試每個方格的有效性,作爲女王可以移動到的三個方法之一,即(square.x == queen.x || square.y == queen.y || square.x - queen.x == square.y - queen.y)。如果你的方格符合上述任何一個規則,那麼它就是一個有效的方格,否則它不是。當然,忽略女王目前居住的廣場(square.x!= queen.x && square.y!= queen.y)。合理? – ManoDestra