二叉树怪异调试
问题描述:
我在制作程序时遇到了一个调试问题,关于二叉树。在我的程序的主要方法中,我使用构造函数创建一个名为root
的节点,之后我使用getKey()
方法获取应该引用“root”的“previous
”的密钥。二叉树怪异调试
这里是我的代码:
/**
* BinaryTreeExample from Internet
* @author xinruchen
*
*/
import java.util.*;
public class BinaryTreeExample
{
private static Node root;
public BinaryTreeExample(int data)
{
root = new Node(data);
}
public void add(Node parent,Node child, String orientation)
{
if(orientation=="left")
{
parent.setLeft(child);
}
else if (orientation=="right")
{
parent.setRight(child);
}
}
public static void main(String ar[])
{
Scanner sc = new Scanner(System.in);
int times = sc.nextInt();
BinaryTreeExample l1=new BinaryTreeExample(3);
Node previous = root;
String direction = "";
System.out.println(previous.getKey());
}
}
class Node {
private int key;
private Node left;
private Node right;
Node (int key) {
this.key = key;
right = null;
left = null;
} // constructor
public void setKey(int key) {
this.key = key;
}
public int getKey() {
return key;
}
public void setLeft(Node l) {
if (left == null) {
this.left = l;
}
else {
left.left = l;
}
}
public Node getLeft() {
return left;
}
public void setRight(Node r) {
if (right == null) {
this.right = r;
}
else {
right.right = r;
}
}
public Node getRight() {
return right;
}
}
如果所有的事情如预期,它应该输出“3”,但它不是什么也不输出。我检查了我的代码并遵循了我的代码流程,但仍然找不到问题所在。请帮助我,谢谢!
答
当您启动程序时,它将等待用户输入的指令int times = sc.nextInt();
。
一旦给出输入,程序确实按预期打印3
。
+0
噢,谢谢你的帮助! –
答
你不应该使用扫描仪为你硬编码的价值为3和你不使用的时间,或者你应该使用这样
System.out.println("Enter the value");
Scanner sc = new Scanner(System.in);
int times = sc.nextInt();
BinaryTreeExample l1=new BinaryTreeExample(times);
每当你要求输入你应该给它prompt.Although不是强制性的要求,但它会避免当程序等待输入时出现混乱
+0
当然,下次我会注意到它,thx! –
纠正语法 –