决策树java简单代码运行
时间: 2023-07-20 12:45:23 浏览: 75
以下是一个简单的决策树 Java 代码示例:
``` java
import java.util.Scanner;
public class DecisionTree {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// 创建决策树
TreeNode decisionTree = createDecisionTree();
// 开始询问用户
while (true) {
TreeNode current = decisionTree;
while (current.children != null) {
System.out.println(current.question);
String answer = input.nextLine();
current = current.children.get(answer);
}
// 打印最终答案
System.out.println(current.answer);
// 询问用户是否继续
System.out.println("是否继续?(y/n)");
String response = input.nextLine();
if (!response.equalsIgnoreCase("y")) {
break;
}
}
input.close();
}
// 创建决策树
private static TreeNode createDecisionTree() {
TreeNode root = new TreeNode("动物是哺乳动物吗?");
TreeNode node1 = new TreeNode("是");
TreeNode node2 = new TreeNode("有羽毛吗?");
TreeNode node3 = new TreeNode("是");
TreeNode node4 = new TreeNode("是鸟类");
TreeNode node5 = new TreeNode("不是鸟类");
root.children.put("是", node1);
root.children.put("否", node2);
node2.children.put("是", node3);
node2.children.put("否", node5);
node3.children.put("是", node4);
node1.answer = "是哺乳动物";
node4.answer = "是有羽毛的鸟类";
node5.answer = "不是鸟类";
return root;
}
}
class TreeNode {
String question; // 问题
String answer; // 答案
Map<String, TreeNode> children; // 子节点
public TreeNode(String question) {
this.question = question;
this.children = new HashMap<>();
}
}
```
这个示例创建了一个简单的决策树,用于确定一个动物是否是哺乳动物或鸟类。在程序运行时,它会逐步询问用户一系列问题,直到最终确定动物的分类。
阅读全文