猿问

未找到符号:但是例如检查?

class Node {

   String guide;

   // guide points to max key in subtree rooted at node

}


class InternalNode extends Node {

   Node child0, child1, child2;

   // child0 and child1 are always non-null

   // child2 is null if node has only 2 children

}


class LeafNode extends Node {

   // guide points to the key


   int value;

}

所以我有3个不同的课程。节点。以及扩展 Node 的内部节点和叶节点。内部节点具有字段 child0、child1 和 child 2。


但是,当我运行此代码时,即使我在第一个 if 语句中检查了对象的实例。当 p 为节点类型时尝试访问 child0、child1 或 child2 时,我仍然收到“符号未找到错误”?我的逻辑有什么问题吗?


if ( p instanceof LeafNode || p instanceof Node) {

   System.out.println(p.guide);

} else {

   if (p.child2 == null) {

       printAll(p.child0);

       printAll(p.child1);

   } else {

       printAll(p.child0);

       printAll(p.child1);

       printAll(p.child2); 

   }

}


饮歌长啸
浏览 132回答 1
1回答

慕丝7291255

问题是 p 是节点类型而不是InternalNode。您需要做的是将 p 转换为 InternalNode,然后再访问仅存在于 InternalNode 中的变量。if (p instanceof InternalNode) {    InternalNode pInternal = (InternalNode) p;    // access node0 and so on here.}您的代码应如下所示:if ( p instanceof LeafNode || p instanceof Node){    System.out.println(p.guide);} else if (p instanceof InternalNode) {    InternalNode internalNode = (InternalNode) p;     if (internalNode.child2 == null){         printAll(internalNode.child0);         printAll(internalNode.child1);     } else {         printAll(internalNode.child0);         printAll(internalNode.child1);         printAll(internalNode.child2);     }}
随时随地看视频慕课网APP

相关分类

Java
我要回答