棋盘上有8个皇后区

时间:2017-02-25 19:06:55

标签: java n-queens

我是初学者,我正在创建一个程序,将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]);
        }
    }

}

}

1 个答案:

答案 0 :(得分:6)

这个循环不需要存在。

您正在清除整个电路板并仅设置一个电池

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;
        }
    }
}

你应该用

替换整个循环
chessBoardArray[rowValue - 1][columnValue - 1] = 1;