我是一名初學者,我正在創建一個程序,將在棋盤上放置8個皇后。
我必須:棋盤上的8皇后號
1)創建空白棋盤(整數8X8 2D陣列,全0)
2)使用一個循環,要求在板8點上的位置的用戶,具有1在更換0這個位置
3)顯示最終的板
我不必包括任何錯誤檢查或檢查重複的位置。
我的代碼沒有正確存儲值。
只有最後一張打印正確。
package chessboard;
import javax.swing.JOptionPane;
public class ChessBoard {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
int chessBoardArray[][] = new int[8][8];
for (int z = 0; z < 8; z++) {
int rowValue = Integer.parseInt(JOptionPane.showInputDialog("Enter the row value (1-8)"));
int columnValue = Integer.parseInt(JOptionPane.showInputDialog("Enter the column value (1-8)"));
int rowValueFinal = rowValue - 1;
int columnValueFinal = columnValue - 1;
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if (i == rowValueFinal && j == columnValueFinal) {
chessBoardArray[i][j] = 1;
} else {
chessBoardArray[i][j] = 0;
}
}
}
}
for (int k = 0; k < 8; k++) {
if (k < 7) {
System.out.print(chessBoardArray[0][k]);
} else {
System.out.println(chessBoardArray[0][k]);
}
}
for (int k = 0; k < 8; k++) {
if (k < 7) {
System.out.print(chessBoardArray[1][k]);
} else {
System.out.println(chessBoardArray[1][k]);
}
}
for (int k = 0; k < 8; k++) {
if (k < 7) {
System.out.print(chessBoardArray[2][k]);
} else {
System.out.println(chessBoardArray[2][k]);
}
}
for (int k = 0; k < 8; k++) {
if (k < 7) {
System.out.print(chessBoardArray[3][k]);
} else {
System.out.println(chessBoardArray[3][k]);
}
}
for (int k = 0; k < 8; k++) {
if (k < 7) {
System.out.print(chessBoardArray[4][k]);
} else {
System.out.println(chessBoardArray[4][k]);
}
}
for (int k = 0; k < 8; k++) {
if (k < 7) {
System.out.print(chessBoardArray[5][k]);
} else {
System.out.println(chessBoardArray[5][k]);
}
}
for (int k = 0; k < 8; k++) {
if (k < 7) {
System.out.print(chessBoardArray[6][k]);
} else {
System.out.println(chessBoardArray[6][k]);
}
}
for (int k = 0; k < 8; k++) {
if (k < 7) {
System.out.print(chessBoardArray[7][k]);
} else {
System.out.println(chessBoardArray[7][k]);
}
}
}
}
請[編輯]與你看到的輸出VS的期望是什麼 –
你'else'分支覆蓋所有先前存儲的值 - 刪除它(並有一個初始循環,將數組的所有值設置爲0) – UnholySheep
@UnholySheep int []'已經初始化爲0 –