我希望它显示2d数组,然后用用户输入替换数组的部分,但事实并非如此。请帮忙,因为我不知道它有什么问题。
现在它无法正常显示
import java.util.Scanner;
public class d {
public static void printBoard(char[][]board) {
System.out.println(" 1 2 3 4 5 6 7 8 9");
for (int row = 0; row < board.length; row++) {
String ab = "ABCDEFGHIJ";
System.out.println(ab.charAt(row) + " |");
for (int col = 0; col < board[row].length; col++) {
board[row][col] = 'z';
System.out.print(board[row][col] + " ");
}
}
}
public static void main(String[]args){
Scanner k = new Scanner(System.in);
char[][] board = new char[10][10];
printBoard(board);
System.out.println(" board number");
int a= k.nextInt();
System.out.println(" board number");
int x= k.nextInt();
board[a][x] = 'x';
printBoard(board);
}
}
答案 0 :(得分:0)
您目前声明了一个数组board
,但您只根据用户输入分配了一个char
。首先填充board
空格。像,
static char[][] createBoard(int x, int y) {
char[][] board = new char[x][y];
for (char[] row : board) {
Arrays.fill(row, ' ');
}
return board;
}
如果列要排成一行,则在完成您正在迭代的row
时打印换行符。此外,您不希望在打印方法中初始化数组。像,
public static void printBoard(char[][] board) {
String ab = "ABCDEFGHIJ";
System.out.println(" 1 2 3 4 5 6 7 8 9");
for (int row = 0; row < board.length; row++) {
System.out.print(ab.charAt(row) + " |"); // <-- not a newline.
for (char ch : board[row]) {
System.out.printf("%c ", ch);
}
System.out.println(); // <-- done with the current line.
}
}
最后,在board
中使用类似
main
char[][] board = createBoard(10, 10);