I'm trying to create a decision tree from a text file.
public static BTNode<String> fileToTree (String fileName) throws IOException {
BufferedReader file = new BufferedReader(new FileReader(fileName));
BTNode<String> node = new BTNode("", null, null);
BTNode<String> answer = fileToTreeHelper(node, file);
file.close();
return answer;
}
public static BTNode<String> fileToTreeHelper (BTNode<String> node, Scanner fileScanner) throws IOException {
String line;
if(node == null){
node = new BTNode<String>(fileScanner.nextLine(), null, null);
fileToTreeHelper(node, fileScanner);
}else{
if(fileScanner.hasNext()){
if(node.isLeaf()){
node.setData(fileScanner.nextLine());
}
if(node.getLeft() == null) {
line = fileScanner.nextLine();
if(line.contains("?")) {
node.setLeft(new BTNode<String>(line, null, null));
}
if(line.contains(";")) {
node.setLeft(new BTNode<>(line,null, null));
node.setRight(new BTNode<>(fileScanner.nextLine(),null, null));
}
}
if(node.getRight() == null) {
line = fileScanner.nextLine();
if(line.contains("?")) {
node.setRight(new BTNode<String>(line, null, null));
}
if(line.contains(";")) {
node.getLeft().setLeft(new BTNode<>(line,null, null));
node.getLeft().setRight(new BTNode<>(fileScanner.nextLine(),null, null));
node.setRight(new BTNode<String>(line, null, null));
fileToTreeHelper(node.getRight(), fileScanner);
}
}
}
}
return node;
}
This is what I have so far; when I run it the decision tree should look something like this:
Are you a mammal?
Are you bigger than a cat?
Kangaroo;
Mouse;
Do you live underwater?
Trout;
Robin;
But so far all I am getting is this:
Are you a mammal?
Are you bigger than a cat?
Kangaroo;
--
--
Any help on how to do this? I know I need to recursively call this function but this is not working quite well. Any ideas?