I started java this summer and am designing a small game in my free time. The problem I have right now is with a getter. In a Player class I have a getter for an integer “speed“.
Here is the code:
public int getSpeed(){
return this.speed;
}
This integer “speed” is set in a constructor:
public Player(int x, int y, String n, BufferedImage s, int spd) {
super(x, y);
this.name = n;
this.sprite = s;
spd = this.speed;
this.l_x = x;
this.l_y = y;
}
When I try to use the “speed” variable in a movement code:
if (w) {
p_y -= player.getSpeed();
}
I get this error at runtime (thank you Martijn Courteaux):
Exception in thread "Thread-3" java.lang.NullPointerException
at main.gameMain.update(gameMain.java:81)
Where line 81 is the line that the movement code appears on.
I would greatly appreciate any help that I could get as I could make everything “work” by using individual variables for everything, but it would be 10x easier and cleaner if I could know why my getter’s aren’t working.
Thank you in advance!
EDIT: I changed
spd = this.speed;
to
this.speed = spd;
but, I am still getting the Null Pointer Exception Error. In fact any variable that I am trying to use from the throws the same error.
Can anyone see any major errors?
And thanks to everyone that has helped so far! I greatly appreciate it!
package main;
import java.awt.image.BufferedImage;
public class Player extends Character {
private String name;
private BufferedImage sprite;
private int speed, l_x, l_y;
public Player(int x, int y, String n, BufferedImage s, int spd) {
super(x, y);
this.name = n;
this.sprite = s;
speed = spd;
this.l_x = x;
this.l_y = y;
}
public int getSpeed(){
return this.speed;
}
public void setSpeed(int i){
this.speed = i;
}
public int getOriginalX(){
return super.o_loc_x;
}
public int getOringinalY(){
return super.o_loc_y;
}
public int getCurrentY(){
return this.l_y;
}
public int getCurrentX(){
return this.l_x;
}
public void setCurrentY(int i){
i = this.l_y;
}
public void setCurrentX(int i){
i = this.l_x;
}
public void moveUp(){
this.l_y -= speed;
}
public void moveDown(){
this.l_y += speed;
}
public void moveLeft(){
this.l_x -= speed;
}
public void moveRight(){
this.l_x += speed;
}
public void setName(String input){
this.name = input;
}
public String getName(){
return this.name;
}
public void setSprite(BufferedImage m){
this.sprite = m;
}
public BufferedImage getSprite(){
return this.sprite;
}
}
EDIT: I am such an idiot. WHen I was declaring a new instance of Player, I put
Player player =…
Instead of:
player = ….
The NullPointerException is in your gameMain class, so we need to see that to see what the problem might be.
As you have now pointed out in your question the problem was caused by your assignment to the player variable. Instead of assigning to the instance variable you have created a new local variable and assigned to that, thus future access to the instance variable results in a NullPointerException.