用单个类构建“父/子”系统

我正在尝试使用类创建一个类似“骨骼”的系统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_1

right_arm_1

什么时候应该输出...


left_arm_1

left_arm_2

right_arm_1

right_arm_2

如何让程序输出正确的字符串?


动漫人物
浏览 105回答 2
2回答

慕妹3146593

我会使用递归&nbsp; &nbsp;public void printBones(Bone bone) {&nbsp; &nbsp; &nbsp; &nbsp; if(bone == null) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; List<Bone> children = bone.getChildren();&nbsp; &nbsp; &nbsp; &nbsp; if(children != null && children.size() > 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for(Bone bone : children) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; printBones(bone);&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(bone.getName());&nbsp; &nbsp; }

不负相思意

因为body只有 2 个孩子,所以输出只有&nbsp;left_arm_1 &nbsp;right_arm_1如果要打印所有孩子,则需要对孩子的所有孩子进行递归,依此类推。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java