我是 Java 新手,我正在做关于构建决策树的作业。经过2天的不断编码,我终于建树并手动验证。但是我坚持验证树,因为每次我尝试将“节点”对象传递给 Validator 类时,它都是空的。我尝试了各种以前的建议,但似乎没有任何效果。我需要有人指出我的错误以及为什么它是错误的。这是一小部分代码,将解释我想要实现的目标。请就我应该如何处理这个问题提出建议。
//Node Class to represent a node in the tree
public class DecisionTreeNode
{
String attribute;
boolean isLeaf;
DecisionTreeBranch[] branches; //Another class to represent branch from a node
//Default constructor for a Node: With attributes, label and isLeaf condition
public DecisionTreeNode(String attribute)
{
this.attribute = attribute;
this.isLeaf = true;
}
............
}
//Tree class with logic to build the tree
public class BuildDecisionTree
{
public PrepareFile config; //Need this object to get a arraylist of values to construct the tree
DecisionTreeNode root;
BuildDecisionTree(PrepareFile config)
{
this.config = config;
}
//Construct Decision Tree
public void buildDecisionTree()
{
root = myDecisionTreeAlgorithm(config.getExamples(), config.getAttributes());
System.out.println("\n !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!Decision tree was constructed!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n");
root.printDecisionTree("");
}
//This is the validator where is want both the "config" and the "root" objects
import java.util.List;
public class DecisionTreeValidator
{
PrepareFile config;
DecisionTreeNode node;
BuildDecisionTree bTree;
public DecisionTreeValidator(BuildDecisionTree bTree, PrepareFile config)
{
this.bTree = bTree;
this.node = bTree.root; //I tried adding a getter function in BuildDecisionTree class and returned the root, even then this was null. Like below
//this.node = bTree.buildDecisionTree(); //made the return type of the buildDecisionTree function as "DecisionTreeNode"
this.config = config;
this.examples = config.getExamples();
}
public boolean validateSingleExample(Example example)
{
boolean result = true;
while(node.isLeaf == false) //THIS IS WHERE I GET THE NULL POINTER EXCEPTION
...........................
}
}
//Main class
public class PredictRestaurant
{
public static void main(String[] args)
{
PrepareFile config = new PrepareFile();
BuildDecisionTree bTree = new BuildDecisionTree(config);
DecisionTreeValidator validator = new DecisionTreeValidator(bTree, config);
boolean isTrain = true;
config.setTreeParameters();
bTree.buildDecisionTree();
}
}