2013-11-18 3 views
0

У меня есть дерево splay, которое я хочу напечатать в текстовой области. Он печатает на консоли, но я решил добавить графический интерфейс, который я хочу напечатать деревом для textArea.Печать BST в текстовой области в java

public class Bst<Key extends Comparable<Key>, Value> { 
    private Node root; 

    private class Node { 
     private Key phone_number;    
     private Value contact_name;   
     private Node left, right; 
     public Node(Key phone_number, Value contact_name) { 
      this.phone_number = phone_number; 
      this.contact_name = contact_name; 
     } 
    } 
    public boolean contains(Key phone_number) { 
     return (get(phone_number) != null); 
    } 

    // return contact_name associated with the given phone_number 

    public Value get(Key phone_number) { 
     root = splay(root, phone_number); 
     int cmp = phone_number.compareTo(root.phone_number); 
     if (cmp == 0) 
      return root.contact_name; 
     else 
      return null; 
    } 


    public void printTree() 
    { 
     if(isEmpty()) 
      System.out.println("Empty tree"); 
     else 
      printTree(root);   
    } 

    private void printTree(Node t) 
    { 
     if (t.left != null) 
     { 
      System.out.println("Phone Number:" + t.phone_number.toString() + " Contact Name : " + t.contact_name.toString()); 
      printTree(t.left); 
     } 

     if (t.right != null) 
     { 
       printTree(t.right); 
       System.out.println("name:" + t.phone_number.toString() + " Number : " + t.contact_name.toString() ); 
     } 
    } 
} 

В настоящее время мой printTree имеет недействительный тип возврата, как показано выше.

Как я могу изменить свой код, чтобы иметь возможность печатать все значения и ключи дерева в TextArea. Я знаю, что setText() принимает строковый тип, но в этом случае это не сработает (я думаю), как я могу убедиться, что метод печати выводит все значения в текстовую область?

+1

хотя бы полный текст сообщения. – Makky

+0

Я бы перешел в 'StringBuilder' и просто называет' append' там, где есть 'System.out' – Danny

+0

. Кажется, это хорошая ситуация для реализации шаблона посетителя. –

ответ

0

Вот код, в котором вы нуждаетесь. Обратите внимание, что теперь ваш метод no-arg printTree() возвращает строку, которую вы можете использовать для печати дерева в другом месте.

public class Bst<Key extends Comparable<Key>, Value> { 
    private Node root; 

    private class Node { 
     private Key phone_number;    
     private Value contact_name;   
     private Node left, right; 
     public Node(Key phone_number, Value contact_name) { 
      this.phone_number = phone_number; 
      this.contact_name = contact_name; 
     } 
    } 
    public boolean contains(Key phone_number) { 
     return (get(phone_number) != null); 
    } 

    // return contact_name associated with the given phone_number 

    public Value get(Key phone_number) { 
     root = splay(root, phone_number); 
     int cmp = phone_number.compareTo(root.phone_number); 
     if (cmp == 0) 
      return root.contact_name; 
     else 
      return null; 
    } 


    public String printTree() 
    { 
     if(isEmpty()) 
      return "Empty tree"; 
     else 
     { 
      StringBuilder sb = new StringBuilder(); 
      printTree(root, sb); 
      return sb.toString(); 
     } 
    } 

    private void printTree(Node t, StringBuilder sb) 
    { 
     if (t.left != null) 
     { 
      sb.append("Phone Number:" + t.phone_number.toString() + " Contact Name : " + t.contact_name.toString()); 
      printTree(t.left, sb); 
     } 

     if (t.right != null) 
     { 
       printTree(t.right, sb); 
       sb.append("name:" + t.phone_number.toString() + " Number : " + t.contact_name.toString() ); 
     } 
    } 
} 
+0

спасибо человеку. это то, что мне нужно. – marengz

0

Вы можете использовать следующий код. Реализация toString() позволяет забыть о любой дополнительной печати строки, которую вы получаете из printTree(). Вы сможете просто распечатать объект.
И, кстати, если «Value» и «Key» реализуют toString(), тогда нет необходимости называть его, вы можете просто использовать их в строке с оператором «+».

public String toString() 
{ 
    return printTree(); 
} 

public String printTree() 
{ 
    String str; 
    if(isEmpty()) 
     str = "Empty tree"; 
    else 
     str += printTree(root); 
} 

private String printTree(Node t) 
{ 
    String str = ""; 
    if (t.left != null) 
    { 
     str += "Phone Number:" + t.phone_number + " Contact Name : " + t.contact_name + "\n"; 
     str += printTree(t.left); 
    } 
    if (t.right != null) 
    { 
     str += printTree(t.right); 
     str += "name:" + t.phone_number + " Number : " + t.contact_name + "\n"; 
    } 
    return str; 
} 
Смежные вопросы