I am a beginner and I am creating a program which will place 8 queens on a chessboard.
I must:
1) Create a blank chessboard (8X8 2D array of integers, all 0's)
2) Using a loop, ask the user for 8 locations on the board, replace the 0 with a 1 at this location
3) Display the final board
I do not have to include any error checking or checking for duplicate locations.
My code does not store the values properly.
Only the last one gets printed correctly.
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]);
}
}
}
}
This loop doesn't need to exist.
You are clearing the entire board and setting only one cell
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;
}
}
}
You should replace that entire loop with
chessBoardArray[rowValue - 1][columnValue - 1] = 1;