When calling the method setPiece(int x, int y, char piece) in the main method, I want the board to be filled with a character giving in the argument, but for some reasons, I am not getting what I expected when I print the board out after calling the method.
public class TicTacToe {
private char[][] board;
public TicTacToe() {
board = new char[3][3];
for (int r = 0; r < 3; r++) {
for (int c = 0; c < 3; c++) {
board[r][c] = ' ';
}
}
}
public void setPiece(int x, int y, char piece){
board[x][y] = piece;
}
public String toString(){
String result = "";
for (int r = 0; r < 3; r++) {
for (int c = 0; c < 3; c++) {
board[r][c] = ' ';
System.out.print(board[r][c] + " | ");
}
System.out.println();
}
return result;
}
public static void main(String[] args) {
TicTacToe board = new TicTacToe();
board.setPiece(1, 2, 'x');
System.out.println(board); //I am expecting here the board to be filled with 'x', but it won't work so.
}
}
What have I done wrong here? How should I rewrite my method to get the result I want?
In toString
board[r][c] = ' '; is wrong
public String toString() {
String result = "";
for (int r = 0; r < 3; r++) {
for (int c = 0; c < 3; c++) {
System.out.print(board[r][c] + " | ");
}
System.out.println();
}
return result;
}