2013-10-17 84 views
1

我的代碼下面我定義了一個嵌套類時出了什麼問題? 它抱怨說:CNode不能解析爲一個類型Java:無法解析到一個類型

package compute; 

public class CBTree { 

    public CNode root; 

    public void addNode(int key){ 
     CNode newNode = new CNode(key); 
     // now to find an appropriate place for this new node 

// 1 it could be placed at root 
     if (null == root){ // to void c-style mistakes a==null (with a=null) is not prefered 
     root = newNode; 
     } 
// if not then find the best spot (which will be once of the 
     CNode currentRoot = root; 
     while(true){ 
     if (key < currentRoot.key){ 
      if (null == currentRoot.left){ 
       currentRoot.left = newNode; 
       break; 
      } else{ 
       currentRoot = currentRoot.left; 
      } else{//if (key < currentRoot.key) 
       if (null == currentRoot.right){ 
        currentRoot.right = newNode; 
        break; 
       }else{ 
        currentRoot = currentRoot.right; 
       } 

      } 

     }//while 



     class CNode{ 
      int key; 
      public CNode left; 
      public CNode right; 
      /** 
      * Constructor 
      */ 
      public CNode(int key){ 
       this.key = key; 
      } 
      /** 
      * Display the node 
      */ 
      public void display(){ 
       System.out.println("node:"+ key); 
      } 

     } 


     } 

回答

3

CNode類在addNode方法定義。

將您的CNode類放在addNode方法之外,以便可以解決。

此外,您將需要調整您的if/else邏輯,因爲您目前在同一個if上有兩個else塊,它們將不會編譯。

+0

opps!我沒有注意到它,因爲我用記事本並將代碼粘貼到eclipse上 –

1

除了rgettman的建議,您還可以使CNode成爲CBTree中的一個靜態類,並使用CBTree.CNode實例化它。

此外,您的包圍看起來不對。你的評論結束你的while塊似乎對應於你的if塊。

此問題與this非常相似。需要被放置在addNode方法

class CNode{ 
       int key; 
       public CNode left; 
       public CNode right; 
       /** 
       * Constructor 
       */ 
       public CNode(int key){ 
        this.key = key; 
       } 
       /** 
       * Display the node 
       */ 
       public void display(){ 
        System.out.println("node:"+ key); 
       } 

      } 
0

下面的代碼內的方法是指任何能力之前或之後,方法運行將失敗指的是類。把你的嵌套類放入你的主類中,但不包含任何方法。

1

把嵌套類以外

+0

沒有意識到這已經被回答。對不起,發佈太快了。 – 2013-10-17 18:14:15

相關問題