[英]java program printing weird hexadecimal output
好的,我正在嘗試為二進制搜索樹編寫程序。 一切看起來都不錯,除了我的程序一直在打印這個,而不是我在整數上的有序遍歷。我試圖在main方法中只使用println並得到同樣的東西?
這是我的代碼:
public class bst {
Node root;
public Node getRoot(){
return root;
}
public bst(){
root=null;
}
//method addNode
public void insert(int key){
Node newNode= new Node(key);//initialize Node
if(root==null){
root=newNode;
}else{
Node focusNode=root;
Node insNode=root;
while(insNode!=null){
focusNode=insNode;
if(key<focusNode.getKey()){
insNode=insNode.getLeft();
}
else{
insNode=insNode.getRight();
}
}
if(key<focusNode.getKey()){
focusNode.setLeft(newNode);
}
else{
focusNode.setRight(newNode);
}
}
}
public void inOrder(Node focusNode){
if (focusNode !=null){
inOrder(focusNode.leftChild);
System.out.println(focusNode);
inOrder(focusNode.rightChild);
}
}
//Node class
class Node{
int key;
Node leftChild;
Node rightChild;
//Node constructor
Node(int key){
this.key=key;
leftChild=null;
rightChild=null;
}
public void setLeft(Node left){
this.leftChild=left;
}
public void setRight(Node right){
this.rightChild=right;
}
public Node getLeft(){return leftChild;}
public Node getRight(){return rightChild;}
public void setKey(int k){this.key=k;}
public int getKey(){return key;}
public void print(){
System.out.println(getKey());
}
}
public static void main(String[] args){
bst theTree= new bst();
theTree.insert(30);
theTree.insert(60);
theTree.insert(50);
theTree.insert(70);
theTree.inOrder(theTree.getRoot());
}
}
在inOrder
方法中,您可以執行以下操作:
System.out.println(focusNode);
您將直接打印focusNode
,因此,除非您的Node
類重寫默認的toString
方法,否則您只會看到對象的哈希碼(如果您有興趣,請參見此問題的詳細信息)。 您可能想要類似
System.out.println(focusNode.getKey());
或者只是使用您編寫的print
方法。
看起來您正在嘗試打印實際的Node,它只是該節點的內存地址。 如果要打印整數,則應將鍵打印到節點。
print(node.getKey());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.