所以我一直在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);
}
}
}
}
沒有,顯然它不是seriazable或任何本meansException線程 「main」 java.io.NotSerializableException:LearningTree $節點 \t在java.io.ObjectOutputStream.writeObject0(來源不明) \t在java.io .ObjectOutputStream.writeObject(Unknown Source) \t at LearningTree.saveNode(LearningTree.java:103) \t at LearningTree.main(LearningTree.java:167) – metelofe