1

下面我定义了一个嵌套类的代码有什么问题?它抱怨说:CNode 无法解析为一个类型

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);
            }

         }


      }
4

4 回答 4

3

CNode类在方法中定义addNode

将您的CNode类放在addNode方法之外,以便可以解决它。

此外,您将需要调整您的 if/else 逻辑,因为您目前else在同一块上有两个块if,它们不会编译。

于 2013-10-17T18:01:26.630 回答
1

除了 rgettman 的建议,您还可以使 CNode 成为 CBTree 中的静态类,并使用 CBTree.CNode 对其进行实例化。

此外,您的包围看起来不正确。您结束 while 块的评论似乎对应于您的 if 块。

这个问题与此非常相似。

于 2013-10-17T18:06:40.350 回答
1

将嵌套类放在方法中意味着在方法运行之前或之后引用该类的任何能力都将失败。将嵌套类放在主类中,但在任何方法之外。

于 2013-10-17T18:12:25.580 回答
0

下面的代码需要放在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);
                }

             }
于 2013-10-17T18:07:30.250 回答