2016-12-24 1 views
-1

프로그램을 만들 때 디버깅 문제가 발생하여 이진 트리가 발생했습니다. 내 프로그램의 main 메소드에서 constructor을 사용하여 root이라는 노드를 만들고, 그 후에 메서드를 사용하여 "previous"의 키를 가져 와서 "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

예, 다음 번에 내가 알아 차릴 것입니다. –