Zip
Zip

Reputation: 5592

My method of setting in 'piece' in TicTacToe game is not working

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?

Upvotes: 0

Views: 349

Answers (3)

justin
justin

Reputation: 1

public void setPiece(int x, int y, char piece){
    board[x][y] = piece;

}

this method is inputting 3 values.. the third being "char piece"

and inside your code you aree assigning piece to board[x][y]... ( which first of all is assigning a 2d char to a single char. )

there is too much wrong here.

Upvotes: -2

amit
amit

Reputation: 178421

There are two issues here:

  1. Your method setPiece() changes only one square in the board. You need to iterate the entire board if you want to change everything in the board - but that does not make sense for the method's name and arguments.
  2. Your toString() method mutates the array and set it back to ' '. for each element.This behavior is usually unadvised.

Upvotes: 1

Melih Altıntaş
Melih Altıntaş

Reputation: 2535

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

Upvotes: 3

Related Questions