This site requires JavaScript, please enable it in your browser!
Greenfoot back
michiele
michiele wrote ...

2011/10/3

getKey

michiele michiele

2011/10/3

#
I want to use the getKey() method so that I only get one action (ball is shot) when the space bar is clicked. The following code works:
        String myKey = Greenfoot.getKey();   
      
        if ("space".equals(myKey)){ //add the ball 
            Ball ball = new Ball();             
          getWorld().addObject(ball, getWorld().getWidth() / 2, getWorld().getHeight() - 50);
          ball.setRotation(getRotation()-90);
        } 
but why does this code give me a null pointer exception?
        String myKey = Greenfoot.getKey();   
      
        if (myKey.equals("space")){ //add the ball 
            Ball ball = new Ball();             
          getWorld().addObject(ball, getWorld().getWidth() / 2, getWorld().getHeight() - 50);
          ball.setRotation(getRotation()-90);
        } 
(notice the order of the IF statement.)
mikey mikey

2011/10/3

#
if i knoew, i help
kiarocks kiarocks

2011/10/3

#
it has to do with calling the equals method on an object that is not there. See this video for more details.
danpost danpost

2011/10/4

#
Actually, it has to do with the fact that myKey can be null and most probably will be the first time this statement is reached. Instead of checking to see if myKey equals 'space' , check to see if 'space' equals myKey. Since 'space' is never null, you will avoid the null pointer exception.
You need to login to post a reply.