2016-12-24 4 views
-1

プログラムを作成しているときにデバッグに関する問題が発生しました。私のプログラムのメインメソッドでは、というノードを作成するコンストラクタを使用しています。その後、 "previous"のキーを取得するためにgetKey()メソッドを使用します。これは "root"を参照する必要があります。ここでバイナリツリー奇妙なデバッグ

は私のコードです:

/** 
* 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」が、それは代わりに何も出力しないはずです。私は自分のコードをチェックし、コードの流れに従ったが、問題がどこにあるのかまだ分からない。助けてください、ありがとう!

+0

修正された文法 –

答えて

0

プログラムを起動すると、指示がint times = sc.nextInt();のユーザー入力を待ちます。

入力が完了すると、プログラムは3を期待どおりに印刷します。

+0

ああ、ありがとう! –

0

ハード3としての価値をコード化しているとして、あなたがスキャナを使用しないでください、あなたは時間を使用していないか、あなたが入力を要求するたびに、あなたはprompt.Althoughそれ与える必要があり、この

 System.out.println("Enter the value"); 
     Scanner sc = new Scanner(System.in); 
     int times = sc.nextInt(); 

     BinaryTreeExample l1=new BinaryTreeExample(times); 

のように使用する必要があります必須ではありませんが、プログラムが入力を待っているときのような混乱を避けることができます

+0

確かに、私はそれを気づくでしょう、thx! –