以下是部分代码:
Airplane , BigAirplane, Bee都继承超类FlyingObject
用注释里面代码会在其他部分报错,提示paint方法里面enemies 空指针异常...
主要就是加粗的那2段代码,注释掉的那段会出现enemies可能得到null,这是为什么呢
public class World extends JPanel
{
Sky sky=new Sky();
Hero hero= new Hero();
FlyingObject enemies[]= {};
Bullet bullets[]= {};
public FlyingObject nextOne()
{
Random rand=new Random();
int type=rand.nextInt(100);
if(type<45)return new Airplane();
else if(type<80)return new BigAirplane();
else return new Bee();
}
public void enterAction()
{
** /*
enemies=Arrays.copyOf(enemies, enemies.length+1);
enemies[enemies.length-1]=nextOne();
*/
FlyingObject obj=nextOne();
enemies=Arrays.copyOf(enemies, enemies.length+1);
enemies[enemies.length-1]=obj;**
}
public void stepAction()
{
sky.step();
hero.step();
for(int i=0;i<enemies.length;i++)
enemies[i].step();
for(int i=0;i<bullets.length;i++)
bullets[i].step();
}
private void action()
{
Timer timer=new Timer();
timer.schedule(new TimerTask() {
public void run()
{
enterAction();
stepAction();
repaint();
}
}, 10,10);
}
public void paint (Graphics g)
{
sky.paint(g);
hero.paint(g);
for(int i=0;i<enemies.length;i++)
enemies[i].paint(g);
for(int i=0;i<bullets.length;i++)
bullets[i].paint(g);
}
public static void main(String[] args)
{
World world=new World();
JFrame f=new JFrame();
f.add(world);
f.setSize(400,700);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
world.action();
}
}