数组处理中的空指针异常。尝试了一切

时间:2014-12-28 15:00:09

标签: processing

我正在制作一个2D侧滚动游戏而且我被卡住了。我正在为将要产生的对象编写类,而玩家必须避免这样做。但遗憾的是我得到了一个N​​ullpointerexception并且我无法弄清楚为什么。在我清理主要代码并将其转换为类之前,整个过程正在发挥作用。我想我正在初始化数组,没有变量未定义。我过去几个月一直在使用处理器,所以我可能会监督一些事情。

非常感谢你的帮助

 public class Blockfield {
    private int Blockcount;
    private PImage Blockpic;
    private Block block[];

  //Constructor
  public Blockfield (int Blockcount) {
    this.Blockcount = Blockcount; 
    //new array
    block = new Block [Blockcount];
    for ( int i=0; i < Blockcount; i++) {
      block[i] = new Block( width+Blockpic.width, random (height));
    }
  }


  //Draw method for this class
  public void draw () {
    for (int i =frameCount/100; i >0; i--) {
      image ( Blockpic, block[i].x, block[i].y);
      //moves blocks right to left
      block[i].x -=7 ;
      //spawns block when they leave the screen
      if (block[i].x < 0) {
        block[i] = new Block( width+Blockpic.width, random (height));
      }
    }
  }
}

class Block {
float x, y;

Block ( float x, float y) {
this.x= x;
this.y= y;
}
}

主:

Blockfield blockfield;
PImage Blockpic;



void setup () { 
  size (1291, 900);
  blockfield = new Blockfield(100);

  Blockpic = loadImage("block2.png");
}


void draw () {
  background ( 10);

}

1 个答案:

答案 0 :(得分:0)

问题是我在分配Blockpic.width之前尝试在Blockfield构造函数中访问Blockpic。解决方案是在类的构造函数中加载Image。

工作代码:

public class Blockfield {
    private int Blockcount;
    private PImage Blockpic;
    private Block block[];

  //Constructor
  public Blockfield (int Blockcount) {
    this.Blockcount = Blockcount; 
    Blockpic = loadImage("block2.png");
    //new array
    block = new Block [Blockcount];
    for ( int i=0; i < Blockcount; i++) {
      block[i] = new Block( width+Blockpic.width, random (height));
    }
  }


  //Draw method for this class
  public void draw () {
    for (int i =frameCount/100; i >0; i--) {
      image ( Blockpic, block[i].x, block[i].y);
      //moves blocks right to left
      block[i].x -=7 ;
      //spawns block when they leave the screen
      if (block[i].x < 0) {
        block[i] = new Block( width+Blockpic.width, random (height));
      }
    }
  }
}

class Block {
float x, y;

Block ( float x, float y) {
this.x= x;
this.y= y;
}
}

感谢大家的帮助!!!