1

I have a cell object with function

public class Cell {
    static int X;
    static int Y;
    static int Val = 0;
    static int Player = 0;

    public Cell(int a, int b, int p) {
        // TODO Auto-generated constructor stub
        X = a;
        Y = b;
        Val = 0;
        Player = p;
    }

With additional function updateX, updateY, updateVal, updatePlayer and respective get functions. It is called by

    Cell[][] grid = new Cell[7][6];
    for(int i = 0; i < 7; i++)
            for(int j = 0; j < 6; j++)
            {
            grid[i][j] = new Cell(i, j, 0);         
            }       
        System.out.println("wasd");
        grid[0][1].updatePlayer(1); 
        grid[0][1].updateVal(1);

        System.out.println("grid[0][1].getval = " + grid[0][1].getVal() + " grid[1][1].getval = " + grid[1][1].getVal());

But the output is

grid[0][1].getval = 1 grid[1][1].getval = 1

and should be

grid[0][1].getval = 1 grid[1][1].getval = 0

What is causing this error?

1
  • Don't use static variables and methods unless you've got good reason for doing so -- you don't and as a matter of fact have strong reason for not doing this. Commented Feb 9, 2012 at 2:34

3 Answers 3

2
static int X;
static int Y;
static int Val = 0;
static int Player = 0;

These properties should not be static,following code should be ok:

int X;
int Y;
int Val;//the default int value is zero 
int Player;
Sign up to request clarification or add additional context in comments.

Comments

2

You made the X, Y, Val and Player variables in the class static. Which means they are shared by all instances of that class, which means their values in all those instances will be exactly the same. I'm pretty sure you wanted to declare those as instance variables instead:

public class Cell {
    private int x, y, val, player;
    // ...
}

1 Comment

It's not just the x and y fields -- he's made all the fields static when none should be.
2

You made Val a static variable, so only one Val variable exists and it is shared by all Cell objects.

change:

static int Val = 0;

to:

int Val = 0;

Similarly if you want individual Cell objects to retain separate instances of your variables (i.e. x,y,Val) you need to take away the static keyword from all of them

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.