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

2017/5/8

Help java.lang.NullPointerException: String is null

CodeBoy CodeBoy

2017/5/8

#
I keep getting this error when I try to run my code and cannot figure out how to mend it. World class
public Garden()
    {    
        // Create a new world with 600x400 cells with a cell size of 1x1 pixels.
        super(600, 400, 1);
        
        Score.setScore(0);
        Score.addToWorld(this, 800, 20);
        
        Lives.setLives(3);
        Lives.addToWorld(this, 800, 40);
        
        WordBank1.addToWorld(this, 340, 200 );
    }
if (Greenfoot.isKeyDown("enter"))
        {
            if (Typed == WordBank1.Word)
            {
                Score.add(1);
            }
            else
            {
                Lives.minus(1);
            }
        }
WordBank class
public final class WordBank1
{ 
    
    private static int Random;
    private static String[] EasyWords = {"easy", "win", "ball", "bed", "old", "good", "pan",
        "pet", "not", "play", "home", "into", "dog", "came", "run", "bath", "tub", "rip",
        "car", "stop", "go"};
    public static String Word;
    private static Actor wordDisplay;
    
    public static void newWord()
    {
        Random = Greenfoot.getRandomNumber(19);
        Word = EasyWords[Random];
        updateDisplay();
    }
    
    public static void updateDisplay()
    {
        if (wordDisplay == null) wordDisplay = new WordDisplay();
        GreenfootImage image = new GreenfootImage(160, 50);
        image.setColor(Color.RED);
        image.setFont(new Font("Calibri", Font.BOLD, 18));
        image.drawString(Word, 10, 25);
        wordDisplay.setImage(image);
    }
    
    public static void addToWorld(World world, int x, int y)
    {
        updateDisplay();
        world.addObject(wordDisplay, x, y);
    }
    
    public static String getWord()
    {
        return Word;
    }
    
    private static class WordDisplay extends Actor
    {
        public void setLocation(int x, int y) {}
    }
}
Can somebody please tell me what is going wrong.
danpost danpost

2017/5/8

#
Change line 30 in the WordBank1 class to this;
newWord();
davmac davmac

2017/5/8

#
Can somebody please tell me what is going wrong.
Your "Word" variable is never getting set to any value, so it contains null (no object). When the following line runs:
        image.drawString(Word, 10, 25);
`Word' is still null, so this is an error. You must supply an actual string to the drawString method (even if it is the "empty" string; that is still different from no string at all!). Danpost's suggested change should solve the problem.
You need to login to post a reply.