所以我用Java编写了一个基本的二进制树,并遇到了一个问题。该计划的目标是“学习”新问题,以便猜出类似于20个问题的动物。但是,我不知道如何“保存”节点,以便下次运行时可以通过同一个类调用它。有关如何执行此操作的任何提示或示例? (另外,如果您发现任何其他明显错误,请随时批评/评论)
public class LearningTree {
Node root;
public void addNode(double key, String name){
Node newNode = new Node(key, name);
if (root == null){
root = newNode;
} else {
Node focusNode = root;
Node parent;
while(true){
parent = focusNode;`enter code here`
if(key < focusNode.key){
focusNode = focusNode.leftChild;
if(focusNode == null){
parent.leftChild = newNode;
return;
}
} else {
focusNode = focusNode.rightChild;
if(focusNode == null){
parent.rightChild = newNode;
return;
}
}
}
}
}
public void traverse(Node focusNode){
if(focusNode != null){
traverse(focusNode.leftChild);
traverse(focusNode.rightChild);
}
}
class Node{
double key;
String name;
Node leftChild;
Node rightChild;
Node(double key, String name){
this.key = key;
this.name = name;
}
}
public void keyChange(Node focusNode, double newkey){
focusNode.key = newkey;
}
public Node findNode(double key) {
Node focusNode = root;
while (focusNode.key != key) {
if (key < focusNode.key) {
focusNode = focusNode.leftChild;
} else {
focusNode = focusNode.rightChild;
}
if (focusNode == null)
return null;
}
return focusNode;
}
public static void main(String[] args){
LearningTree Tree = new LearningTree();
Scanner sc = new Scanner(System.in);
//Nodes
Tree.addNode(1500, "Does it have wings?");
Tree.addNode(750, "Is it a dog?");
System.out.println("Is it an animal?");
double n = 1000;
while(true){
String Answer = sc.nextLine();
String answer = Answer.toLowerCase();
double k = n;
if(answer.equals("y")){
n = 1.5* n;
}
if(answer.equals("n")){
n = .5*n;
}
if(Tree.findNode(n) != null){
System.out.println(Tree.findNode(n).name + " (y/n)");
}
if(Tree.findNode(n) == null){
System.out.println("What is it?");
String answer1 = sc.nextLine();
System.out.println("What would distinguish a " + answer1 + "from the previous guess?");
String answer2 = sc.nextLine();
System.out.println("What would the answer be to " + answer2 + "? (y/n)");
String answer3 = sc.nextLine();
double s;
if(Tree.findNode(k/1.5) == null){
Tree.findNode(k/.5);
} else {
Tree.findNode(k/1.5);
}
if(answer3.equals("y")){
Tree.keyChange(Tree.findNode(k), n );
s = 1.5;
Tree.addNode(n, Tree.findNode(n).name);
}
if(answer3.equals("n")){
Tree.keyChange(Tree.findNode(k), n);
s = .5;
Tree.addNode(n, Tree.findNode(n).name );
}
Tree.addNode(k, answer2);
}
}
}
}
答案 0 :(得分:0)
您可能希望将此对象序列化为文件,以便下次通过反序列化运行时可以将数据恢复。检查ObjectOutputstream类的文档。说过你需要有一些逻辑,
答案 1 :(得分:0)
也许您可以使用本地文件并序列化数据。 Java处理得非常好。
注意:我没有测试过这段代码,但它是一个起点。
private void saveNode(Node n){
FileOutputStream fout = new FileOutputStream("file.txt");
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(n);
oos.close();
}
private Node readNode(){
FileInputStream fin = new FileInputStream("file.txt");
ObjectInputStream ois = new ObjectInputStream(fin);
Node n = (Node)ois.readObject();
ois.close();
return n;
}