player.getX() 返回 null

player.getX() returning null

我有一个函数可以获取玩家 X 坐标然后 returns 他们,但由于某种我不太明白的原因它返回 null。 (这就是我来这里的原因)。

我得到的确切错误如下:

java.lang.NullPointerException
at dev.colors.level.Level.getXOffset(Level.java:78)

我所做的就是调用它,这是第 78 行:

if(player.getX() <= half_width){

这条线来自这个方法:

public int getXOffset(){
    int offset_x = 0;
    //the first thing we are going to need is the half-width of the screen, to calculate if the player is in the middle of our screen
    int half_width = (int) (Game.WINDOW_WIDTH/Game.SCALE/2);

    //next up is the maximum offset, this is the most right side of the map, minus half of the screen offcourse
    int maxX = (int) (map.getWidth()*32)-half_width;

    //now we have 3 cases here
    if(player.getX() <= half_width){
        //the player is between the most left side of the map, which is zero and half a screen size which is 0+half_screen
        offset_x = 0;
    }else if(player.getX() > maxX){
        //the player is between the maximum point of scrolling and the maximum width of the map
        //the reason why we substract half the screen again is because we need to set our offset to the topleft position of our screen
        offset_x = maxX-half_width;
    }else{
        //the player is in between the 2 spots, so we set the offset to the player, minus the half-width of the screen
        offset_x = (int) (player.getX()-half_width);
    }

    return offset_x;
}

getX 方法在这里:

public abstract class LevelObject {

protected float x;

public LevelObject(float x, float y) {

    System.out.println(x);

    this.x = x;
    this.y = y;

public float getX() {
    System.out.println(this.x);
    return x;
  }
}

我们通过创建一个 Player 对象来声明 LevelObject:

player = new Player(128, 64);

然后通过Player.javaclass传递两个变量,然后通过Character.javaclass:

public class Player extends Character {


public Player(float x, float y) throws SlickException {

    super(x, y);

}

Character.java:

public abstract class Character extends LevelObject {

public Character(float x, float y) throws SlickException {
    super(x, y);
}

}

一切正常,直到我们调用 getX(在 LevelObject class 中,即使我在调用 getX 之前使用 System.out 从 LevelObject 打印 "this.x" returns Player 对象声明的正确变量“128.0”。

为了让事情变得更奇怪,如果我在 getX 方法中放置一些打印行,它们不会显示在控制台中。好像连运行方法都没有

这对我来说没有任何意义,我非常迷茫。

显然,player 变量为空。 getXOffset() 没有初始化一个 player 变量,所以我猜它一定是一个 class 字段或其他东西,必须用不同的方法初始化。 也许您需要将 this 关键字添加到播放器初始化代码中(使其看起来像 this.player = new Player(128, 64);)?

无论如何,您的 player 变量未正确初始化,这就是该异常的原因。