我正在嘗試使用類創建一個類似“骨骼”的系統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());
}

不負相思意
TA貢獻1777條經驗 獲得超10個贊
因為body
只有 2 個孩子,所以輸出只有 left_arm_1 right_arm_1
如果要打印所有孩子,則需要對孩子的所有孩子進行遞歸,依此類推。
添加回答
舉報
0/150
提交
取消