2016-12-24 88 views
-1

我在製作程序時遇到了一個調試問題,關於二叉樹。在我的程序的主要方法中,我使用構造函數創建一個名爲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」,但它不是什麼也不輸出。我檢查了我的代碼並遵循了我的代碼流程,但仍然找不到問題所在。請幫助我,謝謝!

+0

糾正語法 –

回答

0

當您啓動程序時,它將等待用戶輸入的指令int times = sc.nextInt();

一旦給出輸入,程序確實按預期打印3

+0

噢,謝謝你的幫助! –

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! –