亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

用單個類構建“父/子”系統

用單個類構建“父/子”系統

動漫人物 2022-10-07 19:34:56
我正在嘗試使用類創建一個類似“骨骼”的系統Bone,并讓“主要”骨骼的孩子由所有其他連接的骨骼組成。public class Main {    public static void main(String[] args) {        Bone body = new Bone("primary", null);        Bone leftArm1 = new Bone("left_arm_1", body);        Bone leftArm2 = new Bone("left_arm_2", leftArm1);        Bone rightArm1 = new Bone("right_arm_1", body);        Bone rightArm2 = new Bone("right_arm_2", rightArm1);        List<Bone> bones = new ArrayList<Bone>();        for(Bone child : body.getChildren()) {            System.out.println(child.getName());        }    }}public class Bone {    private Bone parent = null;    private String name = null;    private List<Bone> children = new ArrayList<Bone>();    public Bone(String name, Bone parent) {        this.name = name;        this.parent = parent;        if(parent != null) {            parent.addChild(this);        }    }    public String getName() {        return this.name;    }    public Bone getParent() {        return this.parent;    }    public boolean hasParent() {        if(this.parent != null) {            return true;        } else {            return false;        }    }    public List<Bone> getChildren() {        return this.children;    }    public boolean hasChildren() {        if(this.children.isEmpty()) {            return false;        } else {            return true;        }    }    public void addChild(Bone child) {        this.children.add(child);    }}當前程序正在輸出...left_arm_1right_arm_1什么時候應該輸出...left_arm_1left_arm_2right_arm_1right_arm_2如何讓程序輸出正確的字符串?
查看完整描述

2 回答

?
慕妹3146593

TA貢獻1820條經驗 獲得超9個贊

我會使用遞歸


   public void printBones(Bone bone) {

        if(bone == null) {

            return;

        }


        List<Bone> children = bone.getChildren();

        if(children != null && children.size() > 0) {

            for(Bone bone : children) {

                printBones(bone);  

            }

        }


        System.out.println(bone.getName());

    }


查看完整回答
反對 回復 2022-10-07
?
不負相思意

TA貢獻1777條經驗 獲得超10個贊

因為body只有 2 個孩子,所以輸出只有 left_arm_1  right_arm_1

如果要打印所有孩子,則需要對孩子的所有孩子進行遞歸,依此類推。


查看完整回答
反對 回復 2022-10-07
  • 2 回答
  • 0 關注
  • 122 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號