動(dòng)漫人物
2022-10-07 19:34:56
我正在嘗試使用類創(chuàng)建一個(gè)類似“骨骼”的系統(tǒng)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); }}當(dāng)前程序正在輸出...left_arm_1right_arm_1什么時(shí)候應(yīng)該輸出...left_arm_1left_arm_2right_arm_1right_arm_2如何讓程序輸出正確的字符串?
2 回答

慕妹3146593
TA貢獻(xiàn)1820條經(jīng)驗(yàn) 獲得超9個(gè)贊
我會(huì)使用遞歸
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());
}

不負(fù)相思意
TA貢獻(xiàn)1777條經(jīng)驗(yàn) 獲得超10個(gè)贊
因?yàn)?code>body只有 2 個(gè)孩子,所以輸出只有 left_arm_1 right_arm_1
如果要打印所有孩子,則需要對(duì)孩子的所有孩子進(jìn)行遞歸,依此類推。
添加回答
舉報(bào)
0/150
提交
取消