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

2011/7/2

On Adding to Lists

danpost danpost

2011/7/2

#
I started a scenario that has a List variable in the world.class; but I cannot figure out how to add String entries into the list. I keep getting a NullExceptionPointer message. The basic code producing the error is:
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.util.*;

public class myWorld extends World
{
    public List<String>listData;

    public myWorld()
    {    
        super(550, 330, 1);
        boolean itemAdded = listData.add("First item");
    }
    
    public void act() { }
}
What action do I need to take to correct the problem? AnyOne? (Thanx) I also tried removing first part of line 11: 'boolean itemAdded = '
webmessia webmessia

2011/7/2

#
For Lists I'm not so sure but I know that for ArrayLists you need to construct the list object. As you're importing all of util already you can just change line 6 to
public ArrayList<String> listData = new ArrayList<String>();
That should fix the problem.
danpost danpost

2011/7/2

#
That will work for my purposes! Thank you very much, webmessia! May God's blessings be upon you. :+)
mjrb4 mjrb4

2011/7/4

#
When you declare a field such as you had originally, you're essentially declaring a space that fits a particular type, in this case a list. You haven't actually put a list there yet, that comes when you do:
listData = new ArrayList<String>();  
That way you've created a new object and assigned it to listData, and you can manipulate it by calling methods (such as add.) When you don't create the object you're trying to manipulate an object that's not there, or "null" - hence NullPointerException. When you see an exception like that, that's almost always what will be going on!
You need to login to post a reply.