我正在greenfoot内部开发这个小行星游戏,我的代码不断吐出一个
java.lang.NullPointerException.
代码如下。第 50 行出现错误:
count = world.numberOfObjects();.
我知道有几篇关于这个错误的帖子,但我对这个错误所做的研究表明,当您尝试使用指向 null 的引用时会发生这种情况。但是,我已经初始化了我的变量,所以我不确定为什么会这样。我对编程还是很陌生,所以我可能只是没有正确理解这一点。任何帮助都会很棒。谢谢!
public class Rocket extends SmoothMover
{
private static final int gunReloadTime = 5; // The minimum delay between firing the gun.
private static final int protonReloadTime = 500; // The minimum delay between proton wave bursts.
private int reloadDelayCount; // How long ago we fired the gun the last time.
private int protonDelayCount; // How long ago we fired the proton wave the last time.
private int count = 0; //count the number of asteroids
private GreenfootImage rocket = new GreenfootImage("rocket.png");
private GreenfootImage rocketWithThrust = new GreenfootImage("rocketWithThrust.png");
/**
* Initialise this rocket.
*/
public Rocket()
{
reloadDelayCount = 5;
protonDelayCount = 500;
addToVelocity(new Vector(13, 0.7)); // initially slowly drifting
}
/**
* Do what a rocket's gotta do. (Which is: mostly flying about, and turning,
* accelerating and shooting when the right keys are pressed.)
*/
public void act()
{
move();
checkKeys();
checkCollision();
reloadDelayCount++;
protonDelayCount++;
Space space = (Space)getWorld(); //call space objects
World world = getWorld(); //call world objects
count = world.numberOfObjects(); //ERROR IS HERE
/**
* Add an asteroid when the starting ones are cleared
*/
if(count <=2)
{
space.add();
}
}
/**
* Check whether there are any key pressed and react to them.
*/
private void checkKeys()
{
ignite(Greenfoot.isKeyDown("up"));
if (Greenfoot.isKeyDown("left"))
{
turn(-5);
}
if (Greenfoot.isKeyDown("right"))
{
turn(5);
}
if (Greenfoot.isKeyDown("space"))
{
fire();
}
if (Greenfoot.isKeyDown("z"))
{
startProtonWave();
}
}
/**
* Check whether we are colliding with an asteroid.
*/
private void checkCollision()
{
Asteroid a = (Asteroid) getOneIntersectingObject(Asteroid.class);
if (a != null)
{
Space space = (Space) getWorld();
space.addObject(new Explosion(), getX(), getY());
space.removeObject(this);
space.gameOver();
}
}
/**
* Should the rocket be ignited?
*/
private void ignite(boolean boosterOn)
{
if (boosterOn)
{
setImage(rocketWithThrust);
addToVelocity(new Vector(getRotation(), 0.3));
}
else
{
setImage(rocket);
}
}
/**
* Fire a bullet if the gun is ready.
*/
private void fire()
{
if (reloadDelayCount >= gunReloadTime)
{
Bullet bullet = new Bullet (getVelocity(), getRotation());
getWorld().addObject (bullet, getX(), getY());
bullet.move ();
reloadDelayCount = 0;
}
}
/**
* Release a proton wave (if it is loaded).
*/
private void startProtonWave()
{
if (protonDelayCount >= protonReloadTime)
{
ProtonWave wave = new ProtonWave();
getWorld().addObject (wave, getX(), getY());
protonDelayCount = 0;
}
}
}