java如何修改打印板?
我写了一个Tictatcoe游戏
这里我用char [][] board
创建一个3x3
表,然后调用方法printBoard()
。我输入例如X_X_O____
,并用这些字符打印这个表
在changeBoard()
方法中,我想输入board[][]
的坐标,如果有字符_
,这将替换为X
。我在compile中给出坐标,以查看坐标是_
,但是当调用方法printBoard()
时,控制台打印相同的电路板,没有任何更改。我不知道我做错了什么,你能帮帮我吗
import java.util.Scanner;
public class TicTacToe {
private char[][] board = new char[3][3];
private String state;
private int n;
private int m;
private int i;
private int j;
Scanner sc = new Scanner(System.in);
public TicTacToe() {
System.out.print("Enter cells: ");
this.state = sc.nextLine();
}
public void printBoard() {
int nextChar = 0;
System.out.println("---------");
for (i = 0; i < 3; i++) {
System.out.print("| ");
for (j = 0; j < 3; j++) {
board[i][j] = state.charAt(nextChar++);
System.out.print(board[i][j] + " ");
}
System.out.println("|");
}
System.out.println("---------");
}
public void changeBoard() {
while (true) {
System.out.print("Enter the coordinates: ");
n = sc.nextInt();
m = sc.nextInt();
if (n < 1 || n > 3 || m < 1 || m > 3) {
System.out.println("Coordinates should be from 1 to 3!");
} else {
int x = n - 1;
int y = m - 1;
this.i = x;
this.j = y;
if (board[i][j] == '_') {
this.board[i][j] = 'X';
break;
} else {
System.out.println("This cell is occupied! Choose another one!");
}
}
}
// printBoard();
}
}
# 1 楼答案
为什么要为
n, m, i, j
使用字段?如果删除它,代码将更干净此外,在
changeBoard
中更改board
,但在board[i][j] = state.charAt(nextChar++);
行中删除更改。您可以将其从printBoard
移动到构造函数。 我想我想写这样的东西