0

尝试从数组列表中获取树名时出现 Nullpointerexception。我已经测试过仅获得名称,但我仍然收到此错误。我想做的就是知道哪个设备正在切割哪棵树。

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

树类

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; }
    }

//------------------为了方便而缩短--------------------------/ / 想象一下缺失的变量和构造函数

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
    }

}
4

1 回答 1

2

你需要初始化theTrees ArrayList

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

您还遗漏了Tree您在方法中使用的一个参数构造函数main。由于您NullPointerException在访问名称时得到了一个偶数,我假设这个构造函数没有初始化treeName任何一个。

使用构造函数,类应该如下所示:

public class Tree {

   private ArrayList<Tree> theTrees;
   private String treeName;

   public Tree(String treeName) {
      this.treeName = treeName;
      this.theTrees = new ArrayList<Tree>();
   } 
   ...
于 2012-11-07T18:05:45.620 回答