[英]Write from text file to decision tree
我正在嘗試從文本文件創建決策樹。
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;
}
這是我到目前為止所擁有的; 當我運行它時,決策樹應如下所示:
Are you a mammal?
Are you bigger than a cat?
Kangaroo;
Mouse;
Do you live underwater?
Trout;
Robin;
但是到目前為止,我得到的是:
Are you a mammal?
Are you bigger than a cat?
Kangaroo;
--
--
有什么幫助嗎? 我知道我需要遞歸調用此函數,但效果不佳。 有任何想法嗎?
我認為您的算法令人困惑,應該是這樣的:
Node node = new Node(fileScanner.nextLine())
// If the node is a question, it should have 2 subnodes with the answers / nested questions.
if(line.contains("?")){
node.setLeft(fileToTreeHelper(...));
// If there is an option that has only 1 answer, then this should have an if that
// checks if there is a ";" and then create the node or set it as null.
node.setRight(fileToTreeHelper(...));
}
// If it is not a question, then it's just an answer to a previous question and returns.
return node;
我能夠解決。 謝謝。 現在可以完美運行。
public static BTNode<String> fileToTree (String fileName) throws IOException {
BufferedReader file = new BufferedReader(new FileReader(fileName));
BTNode<String> node = null;
Scanner fileScanner = new Scanner (file);
BTNode<String> answer = fileToTreeHelper(fileScanner);
return answer;
}
public static BTNode<String> fileToTreeHelper (Scanner fileScanner) throws IOException {
BTNode node = null;
String line = fileScanner.nextLine();
if(line.contains("?")){
node = new BTNode<String>(line, null, null);
node.setLeft(fileToTreeHelper(fileScanner));
node.setRight(fileToTreeHelper(fileScanner));
}else{
node = new BTNode<String>(line, null, null);
return node;
}
return node;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.