-1

I'm trying to make a space invaders type game in Java, but can't work out why the game won't work. Here's the error

java.lang.NullPointerException
at UFO_Game.checkForHit(UFO_Game.java:131)
at UFO_Game.setup(UFO_Game.java:109)
at UFO_Game.run(UFO_Game.java:44)
at acm.program.Program.runHook(Program.java)
at acm.program.Program.startRun(Program.java)
at acm.program.Program.start(Program.java)
at sun.applet.AppletPanel.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)

and here's the code getting the error.

public void checkForHit(){
    GObject CHECK = getElementAt(Bullet.getX(), Bullet.getY());
    if(CHECK == SHIP){
        removeAll();
    }

By the way, I'm using the ACM stuff like in the Stanford methodology.

  • go to the line it indicated (131) and check any variables there. Are they equal to null? If so you need to either change it to a value or set it equal to nothing. Like `String myString;` – CodeAddict Jan 19 '13 at 00:03
  • Have you instantiated the `UFO_Game` object prior to calling `checkForHit()`? – Porkbutts Jan 19 '13 at 00:03
  • -1 It is your job, as a developer, do determine *which* expression is null; from there is is only a small matter to find out *why* it is null. If you cannot deduce as such from a stack-trace, attach a debugger (a debugger is useful anyway). –  Jan 19 '13 at 00:07
  • Also, *there are many "duplicate" answers that explain what an NPE means and what might cause it in different situations* –  Jan 19 '13 at 00:10
  • http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception –  Jan 19 '13 at 00:11

1 Answers1

3

I suppose that Bullet is a field in your UFO_Game class. It isn't assigned a valid value (object fields are initialized with null). When you try to invoke getX(), a NullPointerException is thrown. To avoid this, initialize the Bullet field when you construct each UFO_Game object.

By the way, methods and field names in Java should start with a lower case letter. Anyone familiar with Java will read Bullet.getX() as an invocation of a static (class) method.

erickson
  • 265,237
  • 58
  • 395
  • 493