K Newman K Newman - 1 year ago 83
Java Question

Object not updating in loop(java)

I have begun creating a small tic tac toe game that every time the lop is gone through again, it should switch between 'X' and 'O' by changing the object location:

int m=0;
Test t=new Test();
User use= t.turn();

char[][] board=new char[3][3];

System.out.println(" 1 2 3");

for(int y=0;y<board.length;y++){

for(int x=0;x<board.length;x++){



However every time it seems to be outputting an 'X'. Why is this and how can I fix it?

UPDATE: I don't know if this is needed, but I have the code from my turn method deciding which object to use:

public User turn(){

User use;
PlayerX playX=new PlayerX();
PlayerO playO=new PlayerO();
Board board=new Board();
int xturn=playX.getTurn();
int oturn=playO.getTurn();

return use;

package TicTacToe;

public class User {

private int XCoord;
private int YCoord;
private int Turn=0;
private char Mark;

public int getX(){
return XCoord;
public int getY(){
return YCoord;

public int getTurn(){
return Turn;

public char getMark(){
return Mark;


Answer Source

The values in board are set by calling use.getMark() inside your for loops. Given the use variable doesn't change this is likely to return the same value each iteration (unless it iterates internally which is likely to show a design flaw). You could change board to User[][] and then get the 'mark' using board[x][y].getMark().

More fundamentally, however, the best way to get your software working is by building unit tests with your code. You should have tests demonstrating that User and Player does what you expect before trying things like printing the board. I would suggest that if you learn to unit test as you develop you'll have far fewer problems and the ones you have will be easier to diagnose and fix. It is a much more sustainable approach than using print statements to diagnose problems.

The model you are using is quite unusual. It's unclear why your method has a board represented by an array that is inaccessible to any other objects. That seems to be pretty pointless. I would suggest you might want classes Board, Player, Move to properly separate out responsibilities.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download