Melky
Melky

Reputation: 167

toString, Nullpointerexception

I'm getting a Nullpointerexception when trying to get the trees name from the arraylist. I've tested just getting the name alone but i'm still getting this error. All i want to do is know which Equipment is cutting which tree.

public class TreeTester {
public static void main(String[] args) {   
    Tree trees = new Tree("Trees");
    Tree tree1 = new Tree("Ash Tree");
    trees.addTree(tree1);

Tree Class

public Class Tree{
    private ArrayList<Tree> theTrees;
    private String treeName;

    //Forgot these
    Tree(String trees //There are more but not relevent) {
        theTrees = new ArrayList<Tree>();
    }

    Tree(String treeName){
        this.treeName = treeName;
    }
    //

    public boolean addTree(Tree newTree){
        theTrees.add(newTree);
        return true;
    }

    @Override
    public String toString(){
        String s = getTreeName();
        return s;
    }

    private String getTreeName() {
        return this.treeName; }
    }

//------------------Shortened for ease--------------------------// Just imagine the missing vars and contructor

public Class Equipment{
    private Tree TreeDetails;
    @Override
    public String toString(){
        String s = "Using " + getEqupiment(); + "to cut " + setCutTree()
    }

    public boolean setCutTree(){
        this.treename = treename.toString(); //Nullpointer issue here
        return this.treecut = true;
        //getEquipment works fine
    }

}

Upvotes: 0

Views: 5173

Answers (1)

cyon
cyon

Reputation: 9538

You need to intialize the theTrees ArrayList

public class Tree {
   private ArrayList<Tree> theTrees = new ArrayList<Tree>();

You have also left out the one argument constructor of Tree that you are using in the main method. Since you are getting a NullPointerException even when accessing the name I assume this constructor does not initialize the treeName either.

With the constructor the class should look something like this:

public class Tree {

   private ArrayList<Tree> theTrees;
   private String treeName;

   public Tree(String treeName) {
      this.treeName = treeName;
      this.theTrees = new ArrayList<Tree>();
   } 
   ...

Upvotes: 2

Related Questions