Reputation: 107
I'm trying to make a game with Java and in the game, the object that moves side ways called 'Pinko' is supposed to fire small objects called 'pellets' when the up or down arrow keys are pressed. It successfully compiles and runs, but every time I press the up or down arrow key, I get an error saying:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at Pinko.move(Pinko.java:75)
at A2JPanel.actionPerformed(A2JPanel.java:102)
at javax.swing.Timer.fireActionPerformed(Unknown Source)
at javax.swing.Timer$DoPostEvent.run(Unknown Source)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
There are seven classes: Application, Constants, JFrame, JPanel, Lovely, Pellet and Pinko.
My code in the move method in Pinko class looks like:
public void move(){
area.x -= speed;
if(area.x <= PINKO_MOVE_AREA_LHS || area.x >= PINKO_MOVE_AREA_RHS){
speed = -speed;
}
if( pelletsFired > 0 ){
for (int i = 0; i < pelletsFired; i++){
pellets[i].move();
}
}
}
And the ActionPerformed method in JPanel class looks like:
public void actionPerformed(ActionEvent e){
createLovely();
if(numberOfLovelies > 0){
for (int i = 0; i < numberOfLovelies; i++){
lovelies[i].move();
}
}
pinko.move();
repaint();
}
I have no idea why I keep getting the error mentioned above. Is there something wrong with the for loop in the move() method in Pinko class?? Any help will be much appreciated...
Upvotes: 0
Views: 114
Reputation: 68715
If you are using an IDE then try to use the debugger to help you understand what is going wrong in your code. Otherwise a few traces can help you debug and nail the problem : Here is the updated code you can try :
public void actionPerformed(ActionEvent e){ createLovely();
if(numberOfLovelies > 0){
for (int i = 0; i < numberOfLovelies; i++){
if(lovelies[i] != null )
lovelies[i].move();
else
System.out.println("ERROR: Null lovelies found at an index : " + i);
}
}
if(pinko != null)
pinko.move();
else {
System.out.println("OOPS pinko is null");
}
repaint();
}
Upvotes: 0
Reputation: 48434
I would bet the NullPointerException happens here:
pellets[i].move();
Have you tried verifying that:
Upvotes: 1