Reputation: 27
So, I have a class Square
and I am trying to use an array for it board
. Here is my code:
public class Square{
public int pcolor;
public int contains;
public int xPos;
public int yPos;
Square(int xp,int yp,int pc,int cont){
xPos=xp;
yPos=yp;
contains=cont;
pcolor=pc;
}
};
Square[] board = new Square[64];
board[0].xPos=0;
This gives me unexpected token: [
on board[0].xpos=0;
. Can anyone help me resolve this?
EDIT:
OK, I moved board[0].xpos=0;
inside a method; now it gives me NullPointerException. What do I do?
Upvotes: 0
Views: 111
Reputation: 18611
All the Square
s in board
are null
and you're trying to access a field of a null Object...
You can initialize the array with:
for(int i = 0; i < board.length; i++)
board[i] = new Square(...something_here...);
Also, I'm not sure what you're trying to do, but you should consider using a Square[][]
!
Upvotes: 0
Reputation: 178521
You are trying to make a statement not inside a method or a static scope.
The statement board[0].xPos = 0;
should [probably] be inside a method.
You also seem to have a redundant };
This code compiles just fine:
public class Square{
public int pcolor;
public int contains;
public int xPos;
public int yPos;
Square(int xp,int yp,int pc,int cont){
xPos=xp;
yPos=yp;
contains=cont;
pcolor=pc;
}
Square[] board = new Square[64];
}
To initialize [and access] elements in board
- you will have to do it in a method or in the constructor.
Upvotes: 3
Reputation: 8900
Well, if you do this correctly you will get NullPointerException
because you didn't create any object yet. My guess is you did some syntax error.
Upvotes: 1