2013-10-24 21 views
0

我需要打印出QuadTree。問題是,我不知道如何實現遞增移動以便能夠可視化樹結構。 目前,我只是看到每個級別的節點在一個新的行。但是,使用這個可視化工具來處理樹是很複雜的。toString()的遞增移位

  @Override public String toString() { 
      StringBuilder result = new StringBuilder(); 
      String NEW_LINE = System.getProperty("line.separator"); 
      String SHIFT = System.getProperty(" "); 

      if (_children != null) { 
       String content = ""; 
       for (QtreeNode<E> node : _children) { 
        content += node.toString() + ","; 
       } 
       result.append("{" + SHIFT + NEW_LINE + 
          content.substring(0, content.length()) + 
          SHIFT + NEW_LINE + "}"); 
      } else if (_items != null) { 
       String content = ""; 
       for (E item : _items) { 
        content += item.toString() + " "; 
       } 
       result.append("[" + content + "]"); 
      } 
      return result.toString(); 
     } 
+0

你有什麼期望'System.getProperty(」「)'做什麼?擁有名爲「」的屬性會很奇怪。在建立一個字符串時(你使用'StringBuilder'),你知道不要使用重複連接也是很奇怪的事情),但是你有兩個循環你可以使用重複的連接... –

+0

@Jon Skeet:事實上,System.getProperty(「」)是我的加入一個轉變。但這是不正確的。這就是我發佈這個話題的原因。 –

+0

那麼你期望什麼「換班」?如果你只是想要一個帶有兩個空格的字符串,只需使用'「」'(一個兩個空格的字符串) - 不需要調用'System.getProperty'。 –

回答

1

提供單獨的toStringWithIndent(INT深度)方法爲您的樹節點,並把它重寫的ToString()內。這個方法會爲每個子節點等遞歸調用相同的方法。

UPD一些示例

class Node { 
    private String name; 
    private List<Node> children; 

    @Override 
    public String toString() { 
     String s = name; 
     for(Node n: children) s += children.toStringWithIndent(1); 
     return s; 
    } 

    private String toStringWithIndent(int depth) { 
     // same as toString() but with indent 
     String s = indentFor(depth) + name; 
     for(Node n: children) s += indentFor(depth) + 
       children.toStringWithDepth(depth + 1); 
     return s; 
    } 

    private static String indentFor(int depth) { 
     StringBuilder b = new StringBuilder(depth); 

     while(depth-- > 0) { 
      b.append(" "); 
     } 

     return b.toString(); 
    } 


} 
+0

你能舉個例子嗎? –

+0

您的意思是:\t return result.toStringWithDepth(depth); \t \t depth ++;在這種情況下,我需要創建toStringWithDepth還是內置函數? –

+0

我已經更新了我的答案。 –