Java 构建一个;“父母/子女”;单类系统

Java 构建一个;“父母/子女”;单类系统,java,recursion,Java,Recursion,我正在尝试使用classBone创建一个类似于“骨骼”的系统,并让“主要”骨骼的子骨骼由所有其他连接的骨骼组成 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

我正在尝试使用class
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());
        }
    }

}
当它应该输出时

left_arm_1
right_arm_1
left_arm_1
left_arm_2
right_arm_1
right_arm_2

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

因为
body
只有两个子项,所以输出仅为
左手臂\u 1右手臂\u 1

如果要打印所有子项,则需要对子项的所有子项使用递归,以此类推。

我将使用递归

   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());
    }
public void打印骨骼(骨骼){
if(bone==null){
返回;
}
List children=bone.getChildren();
if(children!=null&&children.size()>0){
用于(骨骼:儿童){
打印骨(骨);
}
}
System.out.println(bone.getName());
}

您的代码正是按照您的要求执行的:打印“primary”子级的名称。听起来您还希望它打印出孩子们的名字(和孩子们的孩子们的名字,等等)。我建议在
Bone
上使用
printChildren()
方法打印当前骨骼的名称,然后对所有骨骼的子级调用
printChildren()
   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());
    }