我正在尝试制作一个有8x8星号游戏板的程序。用户必须在板上放置八个部件,以便每行中有一个部件,但用户可以输入该部件位于每行中的哪个列。最后,我想在决定每一行放置每个部件的位置后打印出电路板的视觉效果。例如,如果他们输入:4,1,7,0,6,4,3,2对于板的第一行看起来像*** P ****(P =件)其他七行的正确列。在我的代码中,我已经创建了8x8游戏板,并且我已经用0填充了板(不知道如何使它成为星号)。我现在处于需要用户输入的位置,以便将每个部分放在正确的列中,但我正在努力这样做。我感谢所有决定帮助我的人!
public void problem3(){
Scanner in = new Scanner(System.in);
char[][] board = new char[8][8];//Initializes an 8x8 board
//This creates the 8x8 board and fills the board with asterisks
for (char row = 0; row < board.length; row++) {
for (char column = 0; column < board[0].length; column++) {
board[row][column] = '*';
}
for (row = 0; row < 8; row++) { //creates right amount of cells for 8 rows
for (char column=0; column<8; column++) { //creates right amount of cells for the 8 columns
System.out.print(board[row][column] + " "); //prints # of cells
}
System.out.println(); //prints each row on new line
}
}
for (int row = 0; row < 8; row++) {
int col = 0;
System.out.println("In which column would you like to place the queen for column ");
col = in.nextInt();
board[row][col] = 'P'; //mark board with "P"
}
for (int i=0; i<8; i++) { //loops prints board
System.out.println(Arrays.toString(board[i]));
}
}
答案 0 :(得分:1)
当用户输入int数据时,你知道它是上一步中提到的一列行,所以取数据如下:
col = in.nextInt();
board[row][col] = 'P';//mark it with p. You may need to validate input column added by user is in range of 0-7?
打印电路板,如:
for (int i=0; i<8; i++) {
System.out.println(Arrays.toString(board[i]));
}