我有这个Java类作业,它输入了机组人员并显示了他们的信息,我也做了其他类似的案例,但是不确定如何构造这个实例。
我要创建两个使用此主要方法的类Sailor和CrewMember,

import java.util.ArrayList;

public class SailorProgram {

    public static void main(String[] args) {

        Sailor firstSailor = new Sailor("Jimmy", "[email protected]");
        Sailor secondSailor = new Sailor("Rose", "[email protected]");
        Sailor thirdSailor = new Sailor("James", "[email protected]");


        CrewMember firstCrew = new CrewMember();
        CrewMember secondCrew = new CrewMember();

        firstCrew.addCrewMember(firstSailor);
        firstCrew.addCrewMember(secondSailor);

        secondCrew.addCrewMember(thirdSailor);
        secondCrew.addCrewMember(secondSailor);

        System.out.println(" First crew \n" + firstCrew);
        System.out.println(" Second crew \n" + secondCrew);

        secondSailor.setEmail("[email protected]");
        System.out.println(" Second crew \n" + secondCrew);
    }
}


然后打印出来

First crew
Jimmy ([email protected])
Rose ([email protected])

Second crew
James ([email protected])
Rose ([email protected])

Second crew
James ([email protected])
Rose ([email protected])


谢谢!

最佳答案

问题尚不清楚,但我会做一些假设。首先,您的CrewMember类容纳水手,因此更合适的名称是Crew。例如,您可以使用ArrayList<Sailor>来实现此目的。

class Crew {

    private final ArrayList<Sailor> sailors = new ArrayList<>();

    //other things, like constuctor here, if needed

    public void addCrewMember(Sailor s) { //add sailors with this
        sailors.add(s);
    }
}


然后,您的Sailor类非常简单。

class Sailor {

    private String name;
    private String email;

    public Sailor(String name, String email) {
        this.name = name; this.email = email;
    }

    //other methods, like getters here
}


编辑:我注意到您也需要打印对象。为此,您可以使用Object类的toString方法。您的Sailor类的示例:

@Override
public String toString() {
    return name + ", " + email;
}


使用System.out.println(sailor1)将在sailor1上调用此方法。

07-24 17:44