Reputation: 29
I am trying to make a snake-type game in Java.
To do so, I am using lists to keep hold every of the snake's body parts with
ArrayList<SnakeBodyPart> snakeBodyParts = new ArrayList<SnakeBodyPart>();
.
I declare and initiate a variable, SnakeBodyPart SnakeBodyPart = null;
.
I then add a body part to the snake with snakeBodyParts.add(SnakeBodyPart);
.
(Not the most efficient way, I guess, but it'll have to do.)
But for some reason, whenever I run the script, I get
Exception in thread "main" java.lang.NullPointerException
,
and that the error is
at game.Snake.<init>(Snake.java:60)
in the Java console.
I want to know what the problem is. Here is the code for the SnakeBodyPart.
class SnakeBodyPart{
int x,y,direction;
void move(){
if(direction == 0){
y -= 50;
}
if(direction == 1){
x += 50;
}
if(direction == 2){
y += 50;
}
if(direction == 3){
x -= 50;
}
}
}
Thanks in advance!
EDIT:
Line 60 is snakeBodyParts.get(0).direction = 0;
.
Upvotes: 0
Views: 89
Reputation: 3519
You have done this:
SnakeBodyPart snakeBodyPart = null;
Create the object
SnakeBodyPart snakeBodyPart = new SnakeBodyPart();
Since snakeBodyPart
is null
, you are getting NullPointerException
in Line 60
. You are calling get()
method on null
as snakeBodyParts.get(0).direction = 0;
Upvotes: 1