2015-09-26 77 views
0
class Fran 
{ 
    String name; 
    int size; 

    Fran(String name,int size) 
    { this.name=name; this.size=size; } 

    String getName() 
    { return this.name; } 

    int getSize() 
    { return this.size; } 
} 

class Node 
{ 
    Fran fran; 
    Node preNode; 

    Node[] children=new Node[10]; 
    int childCount=0; 
    Node child; 

    /* is there child? */ 
    int isChild=0; 

    Node(Fran fran) 
    { 
     this.fran=fran; 
    } 

    Node(Node preNode,Fran fran) 
    { 
     this.fran=fran; 
     this.preNode=preNode; 
    } 

    void setChild(Node preNode,Node child) 
    { 
     this.preNode=preNode; 
     this.child=child; 
     this.children[childCount]=child; 
     this.isChild=1; 
     this.childCount++; 
    } 

    int getChildCount() 
    { return childCount; } 

    Node preNode() 
    { return this.preNode; } 

    String[] getName() 
    { 
     String[] t=new String[childCount]; 

     if(childCount==0) { 
      t[0]=this.fran.getName(); 
      return t; 
     } 
     else 
     { 
      for(int i=0;i<=childCount-1;i++) 
      { 
       t[i]=children[i].fran.getName(); 
      } 
      return t; 
     } 
    } 

    int[] getSize() 
    { 
     int[] t=new int[childCount]; 

     if(childCount==0) { 
     t[0]=this.fran.getSize(); 
     return t; 
     } 
     else 
     { 
     for(int i=0;i<=childCount-1;i++) 
     { 
      t[i]=children[i].fran.getSize(); 
     } 
     return t; 
     } 
    } 

    String getN() 
    { 
     return this.fran.getName(); 
    } 
} 

void setup() 
{ 
    Fran aa=new Fran("apt",36); 
    Fran bb=new Fran("bpt",26); 
    Fran cc=new Fran("cpt",16); 
    /* Fran dd=new Fran("dpt",56); */ 

    Node a=new Node(aa); 
    Node b=new Node(bb); 
    Node c=new Node(cc); 

    a.setChild(a,b); 
    a.setChild(a,c); 

    print(a.getN()); 

    Node f=b.preNode(); 
    print(f.getN()); 
} 
  • 我想做一个树结构。我想返回一个previouse节点。
  • 节点a-> b,a-> c。并且我想让b.preNode() - > Node a。
  • 但是我有NullpointerException,该如何解决这个问题?

谢谢我想制作一个树形图结构。我想找到一个previouse树

+0

此代码错误标记。它不是java,它看起来像处理。它非常接近java。 – Dov

回答

0

首先,你必须明确地决定你想要做什么。你根本就没有说清楚。是根,b和c是它的孩子吗?或者是根,b是它的孩子,c是b的孩子?

你需要一个add方法,将孩子添加到节点:

Node a = new Node (...); 
Node b = new Node(...); 
a.add(b); // this should hook them together 

add方法应B的家长设置为,和的孩子设置为b。

另外,请注意,你有一些文体错误。你应该删除所有的代码设置变量,并把它们放在构造函数中。目前很难看到创建节点时会发生什么,因为您的代码已遍布整个班级。

您还应该考虑删除Fran类并将数据放入Node中。为什么有两个班?它增加了开销,复杂性,并且似乎没有实现任何东西。这只是风格,但它会清理你的代码很多。