为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

饮歌长啸 2023-08-16 16:16:59
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);    }}
查看完整描述

1 回答

?
慕丝7291255

TA贡献1859条经验 获得超6个赞

问题是 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);

     }

}


查看完整回答
反对 回复 2023-08-16
  • 1 回答
  • 0 关注
  • 131 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号