gpt4 book ai didi

java - 添加和删​​除元素

转载 作者:行者123 更新时间:2023-12-01 20:54:42 26 4
gpt4 key购买 nike

我应该让一位教授担任类(class)的讲师。该方法上方的评论也说明了目标。然而,我很困惑如何去做这件事。我对 java 编程很陌生,所以我决定通过进行“instanceof”比较来检查教授是否在类(class)中。我的方向是正确的还是我错过了什么?谢谢!

  • 接近尾声时,我添加了我刚刚遇到的另外 2 个方法,我相信我错误地实现了 getStudents。最后两种方法要求添加和删除学生。我不确定该学生的键值对是什么。

    公共(public)类(class) Course 实现 Comparable {

    /**
    * course id (unique)
    */
    private int id;
    /**
    * course name
    */
    private String name;
    /**
    * course level
    */
    private int level;
    /**
    * professor teaching the course, null if none
    */
    private String professor;
    /**
    * students enrolled in the course (unique), empty if none
    */
    private HashSet<String> students;

    /**
    * Create a course. Initially there is no professor or student for the
    * course.
    *
    * @param id course id
    * @param name course name
    * @param level course level
    */
    public Course(int id, String name, int level) {
    this.id = id;
    this.name = name;
    this.level = level;
    this.professor = null;
    this.students = new HashSet<>();
    }

    /**
    * Get the course id.
    *
    * @return course id
    */
    public int getId() {
    return id;
    }

    /**
    * Get the course name.
    *
    * @return course name
    */
    public String getName() {
    return name;
    }

    /**
    * Get the course level.
    *
    * @return course level
    */
    public int getLevel() {
    return level;
    }

    /**
    * Get the professor teaching the course.
    *
    * @return the professor, if none, null
    */
    public String getProfessor() {
    return professor;
    }

    /**
    * Get the students enrolled in the course.
    *
    * @return the students, organized by ascending hash codes. if there are no
    * students enrolled the list should be empty.
    */
    public Collection<String> getStudents() {
    return students;
    }

    /**
    * Make a professor the instructor of this course. If another professor was
    * teaching it, that information is lost.
    *
    * @param username the username of the professor
    */
    public void addProfessor(String username) {

    }

    }/**

    • 将学生添加到类(class)中(如果他们尚未注册),
    • 在恒定时间内。*
    • @param username 学生的用户名
    • @return 是否添加该学生*/公共(public) boolean addStudent(字符串用户名){//去做返回假;}

    /**

    • 如果学生已注册,请将其从类(class)中删除,
    • 在恒定时间内。*
    • @param username 要删除的学生的用户名
    • @return true 如果学生被删除, false 如果学生不在类(class)中*/公共(public) boolean removeStudent(字符串用户名){//去做返回假;}

最佳答案

您可以使用instanceof关键字在运行时检查对象是否属于特定类型。在这种情况下,注释指出如果之前设置了某个值,那么该值就会丢失。这意味着您可以简单地将给定值设置为教授,而不进行任何检查

public void addProfessor(String userName) {
professor = userName;
}

关于java - 添加和删​​除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42546070/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com