Sign in to follow this  
Devil0150

Java: NullPointerException

Recommended Posts

Devil0150    156
Hi
I keep getting this error in my code and I can't find how to fix it.
Exception in thread "main" java.lang.NullPointerException
at Field.<init>(Dam.java:73)

Here is part of the code:
[CODE]
class Position
{
boolean isEmpty;
Piece pHere;
int adjPos[]; // adjacent positions
void setPiece(Piece p)
{
isEmpty = false;
pHere = p;
}
Position()
{
adjPos = new int[12];
isEmpty = true;
}
}
class Field
{
Position pos[];
Field()
{
pos = new Position[13];
pos[0].adjPos[0] = 1; //error in this line
pos[0].adjPos[1] = 3;
pos[0].adjPos[2] = 5;
pos[0].adjPos[3] = 6;
}
}
[/CODE]

Share this post


Link to post
Share on other sites
Zael    154
The problem is that when you create your position array,

[color=#000000][code]pos = new Position[13];[/code][/color]

you make the assumption that the array is filled with Position objects. It is not.

You need:

[color=#000000][code]
pos = new Position[13];
pos[0] = new Position(); //set element 0 of Position Array to a Position Object.
pos[0].adjPos[0] = 1;
[/code][/color]


Make sense?

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this