【问题标题】:How to add multiple students to student class?如何将多个学生添加到学生班级?
【发布时间】:2017-02-21 20:38:13
【问题描述】:

我正在尝试创建一个学生类、一个课程类和主类。我正在尝试将学生添加到课程中,当学生添加到课程中时,课程中的学生人数应该增加,当代码运行时,它应该打印课程中学生所遵循的课程详细信息。

我有以下代码: 主类:

public class JavaLecture3 {
    public static final int DEBUG = 0;

    public static void main(String [] args){

        //Student student = new Student(); // Calling default constructor here.
        Course course = new Course();

        student = new Student(21, "Joe", "CSE", "07447832342");

        course = new Course("CSE", "Tom", 5);

        System.out.println("Course Information: ");
        System.out.println("-------------------");
        System.out.println(course);
        System.out.println();
        System.out.println("Student contains: "); // calls student.toString());        
        System.out.println("-------------------");
        System.out.println(student);
    }

}

课程类别:

public class Course {

    ArrayList<Student> studentList;
    private String courseName;
    private String teacher;
    private int noOfStudents;

    //Getters
    public String getCourseName(){
        return this.courseName;
    }
    public int getNoOfStudents(){
        return this.noOfStudents;
    }
    public String getTeacher(){
        return this.teacher;
    }

    //Setters
    public void setCourseName(String courseName){
        this.courseName = courseName;
    }
    public void setNoOfStudents(int noOfStudents){
        this.noOfStudents = noOfStudents;
    }
    public void setTeacher(String teacher){
        this.teacher = teacher;
    }

    /**
     * Default constructor. Populates course name, number of students with defaults
     * 
     */
    public Course(){
        this.noOfStudents = 0;
        this.courseName = "Not Set";
        this.teacher = "Not Set";
        studentList = new ArrayList<Student>();
    }

    /** 
     * Constructor with parameters 
     * @param noOfStudents integer
     * @param courseName String with the Course name
     * @param teacher String with the teacher
    */
    public Course(String courseName, String teacher, int noOfStudents){
        this.courseName = courseName;
        this.teacher = teacher;
        noOfStudents = noOfStudents;
        studentList = new ArrayList<Student>();
    } 

   public static void addStudent(Student newStudent){
        if(studentList.size()==noOfStudents){
            System.out.println("The class is full, you cannot enrol.");
        }
        else {
            studentList.add(newStudent);
        }
    }

    public String toString() {
        return "Course Name: " + this.courseName + " Teacher: " + this.teacher 
                + " Number of Students: " + this.noOfStudents;
    }
}

学生班:

public class Student {
    private String name;
    private int age;
    public String gender = "na";
    private String course;
    private String phoneNo;
    public static int instances = 0;

    // Getters
    public int getAge(){
        return this.age;
    }
    public  String getName(){
        return this.name;
    }
    public String getCourse(){
        return this.course;
    }
    public String getPhoneNo(){
        return this.phoneNo;
    }

    // Setters
    public void setAge(int age){
        this.age = age;
    }
    public void setName(String name){
        if (JavaLecture3.DEBUG > 3) System.out.println("In Student.setName. Name = "+ name);

        this.name = name;
    }
    public void setCourse(String course){
        this.course = course;
    }
    public void setPhoneNo(String phoneNo){
        this.phoneNo = phoneNo;
    }


    /**
     * Default constructor. Populates name,age,gender,course and phone Number 
     * with defaults
     */
    public Student(){
        instances++;
        this.age = 18;
        this.name = "Not Set";
        this.gender = "Not Set";
        this.course = "Not Set";
        this.phoneNo = "Not Set";
    }

    /** 
     * Constructor with parameters 
     * @param age integer
     * @param name String with the name
     * @param course String with course name
     * @param phoneNo String with phone number
    */
    public Student(int age, String name, String course, String phoneNo){
        this.age = age;
        this.name = name;
        this.course = course;
        this.phoneNo = phoneNo;
    }

    /** 
     * Gender constructor
     * @param gender 
     */
    public Student(String gender){
        this(); // Must be the first line!
        this.gender = gender;

    }

    protected void finalize() throws Throwable{
        //do finalization here
        instances--;
        super.finalize(); //not necessary if extending Object.
    } 

    public String toString (){
        return "Name: " + this.name + " Age: " + this.age + " Gender: " 
                + this.gender + " Course: " + this.course + " Phone number: " 
                + this.phoneNo;
    }
}

【问题讨论】:

  • 所以 Course 有一个 addStudent 方法。在这里看起来很有用
  • @MeBigFatGuy 我不明白?
  • public static void addStudent(Student newStudent) 那个方法不应该是静态的!

标签: java class arraylist


【解决方案1】:

参考: http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html?is-external=true

Course.getNoOfStudents 应该只返回 studentList.size()。无需维护单独的变量。

要打印学生列表(来自课程):

for(int i=0;i<studentList.size();i++) System.out.println(studentList.get(i));

【讨论】:

    【解决方案2】:

    由于您在 Course 类中初始化了数组列表,您应该将学生添加到其中。您应该在 Course 中创建一个将对象添加到数组列表的方法,例如:

    public void addStudent(Student s){
        studentList.add(s);
        noOfStudents++;
    }
    

    添加多个学生:

    public void addStudents(Student[] students){
        for(int i = 0; i < students.length; i++){
            studentList.add(students[i]);
        }
    }
    

    您就快到了,只需使用数组列表中为您创建的 .add 方法即可。

    【讨论】:

    • 但是我如何添加多个学生?
    • @anon1234 您可以将一组学生作为参数传递,并将每个学生添加到列表中。马上更新答案。
    • 如何在列表中输入学生的详细信息,目前我只能使用Student students = new Student(21, "Joe", "CSE", "07447832342");从主班输入一名学生
    • 当我将此代码 course.addStudents(students); 放在主类中时,我收到以下错误学生无法转换为学生 []。
    • @anon1234 当然你会得到这个错误,你试图传递一个对象而不是一个对象数组,尝试制作多个学生对象然后将它们分配给一个数组并将该数组传递给方法.例如:Student s1 = new Student(); Student s2 = new Student(); Student[] students = {s1,s2}; 然后调用方法。
    【解决方案3】:
    public class JavaLecture3 {
        public static final int DEBUG = 0;
    
        public static void main(String [] args){
    
            Student student = new Student(); // Calling default constructor here.
            Course course = new Course();
    
            student = new Student(21, "Joe", "CSE", "07447832342");
    
            course = new Course("CSE", "Tom", 5);
            course.addStudent(student);
    
            System.out.println("Course Information: ");
            System.out.println("-------------------");
            System.out.println(course);
            System.out.println();
            System.out.println("Student contains: "); // calls student.toString());        
            System.out.println("-------------------");
            System.out.println(student);
        }
    }
    
    public class Course {
    
        List<Student> studentList;
        private String courseName;
        private String teacher;
        private int noOfStudents;
    
        // Getters
        public String getCourseName() {
            return this.courseName;
        }
    
        public int getNoOfStudents() {
            return this.noOfStudents;
        }
    
        public String getTeacher() {
            return this.teacher;
        }
    
        // Setters
        public void setCourseName(String courseName) {
            this.courseName = courseName;
        }
    
        public void setNoOfStudents(int noOfStudents) {
            this.noOfStudents = noOfStudents;
        }
    
        public void setTeacher(String teacher) {
            this.teacher = teacher;
        }
    
        /**
         * Default constructor. Populates course name, number of students with
         * defaults
         * 
         */
        public Course() {
            this.noOfStudents = 0;
            this.courseName = "Not Set";
            this.teacher = "Not Set";
            studentList = new ArrayList<Student>();
        }
    
        /**
         * Constructor with parameters
         * 
         * @param noOfStudents
         *            integer
         * @param courseName
         *            String with the Course name
         * @param teacher
         *            String with the teacher
         */
        public Course(String courseName, String teacher, int noOfStudents) {
            this.courseName = courseName;
            this.teacher = teacher;
            this.noOfStudents = noOfStudents;
            studentList = new ArrayList<Student>();
        }
    
        public void addStudent(Student newStudent) {
            if (studentList.size() == noOfStudents) {
                System.out.println("The class is full, you cannot enrol.");
            } else {
                studentList.add(newStudent);
            }
        }
    
        @Override
        public String toString() {
            return "Course Name: " + this.courseName + " Teacher: " + this.teacher
                    + " Number of Students: " + studentList.size();
        }
    }
    
    public class Student {
        private String name;
        private int age;
        public String gender = "na";
        private String course;
        private String phoneNo;
        public static int instances = 0;
    
        // Getters
        public int getAge() {
            return this.age;
        }
    
        public String getName() {
            return this.name;
        }
    
        public String getCourse() {
            return this.course;
        }
    
        public String getPhoneNo() {
            return this.phoneNo;
        }
    
        // Setters
        public void setAge(int age) {
            this.age = age;
        }
    
        public void setName(String name) {
            if (JavaLecture3.DEBUG > 3)
                System.out.println("In Student.setName. Name = " + name);
    
            this.name = name;
        }
    
        public void setCourse(String course) {
            this.course = course;
        }
    
        public void setPhoneNo(String phoneNo) {
            this.phoneNo = phoneNo;
        }
    
        /**
         * Default constructor. Populates name,age,gender,course and phone Number
         * with defaults
         */
        public Student() {
            instances++;
            this.age = 18;
            this.name = "Not Set";
            this.gender = "Not Set";
            this.course = "Not Set";
            this.phoneNo = "Not Set";
        }
    
        /**
         * Constructor with parameters
         * 
         * @param age
         *            integer
         * @param name
         *            String with the name
         * @param course
         *            String with course name
         * @param phoneNo
         *            String with phone number
         */
        public Student(int age, String name, String course, String phoneNo) {
            this.age = age;
            this.name = name;
            this.course = course;
            this.phoneNo = phoneNo;
        }
    
        /**
         * Gender constructor
         * 
         * @param gender
         */
        public Student(String gender) {
            this(); // Must be the first line!
            this.gender = gender;
    
        }
    
        protected void finalize() throws Throwable {
            // do finalization here
            instances--;
            super.finalize(); // not necessary if extending Object.
        }
    
        public String toString() {
            return "Name: " + this.name + " Age: " + this.age + " Gender: "
                    + this.gender + " Course: " + this.course + " Phone number: "
                    + this.phoneNo;
        }
    }
    

    【讨论】:

      【解决方案4】:
      public class JavaLecture3 {
      public static final int DEBUG = 0;
      
      public static void main(String [] args){
      
          //Create course object
          Course course  = new Course("CSE", "Tom", 5);
          Scanner scanner = new Scanner(System.in);
      
          String cmd = "Yes";
      
          while(cmd.equals("Yes")){
             Student student = new Student();
      
             System.out.print("Enter a new student? ");
             cmd = scanner.next();
      
             if (cmd.equals("Yes")){
                 //Read student name
                 System.out.print("Enter a student name: ");
                 String name = scanner.next();
                 student.setName(name);
      
                 //Read student Age
                 System.out.print("Enter a student age: ");
                 int age = scanner.nextInt();
                 student.setAge(age);
      
                 //Read student Course
                 System.out.print("Enter a student course: ");
                 String stdent_course = scanner.next();
                 student.setCourse(stdent_course);
      
                 //register the student to the class
                 course.addStudent(student);
             }
          }
      
          scanner.close();
      
          System.out.println("Course Information: ");
          System.out.println("-------------------");
          System.out.println(course.toString());
          System.out.println();
      }
      

      }

      我在 Course 类中对您的 toString() 方法做了一些修改。这应该会打印出上课的学生名单。

      public String toString (){
          String ret_value =  "Name: " + this.name + " Age: " + this.age + " Gender: " 
                  + this.gender + " Course: " + this.course + " Phone number: " 
                  + this.phoneNo + " Students attending this course:";
      
          for (Student student: studentList) {
              ret_value = ret_value + " " + Student.getName();
          }
      
          return ret_value;
      }
      

      【讨论】:

      • 但是我如何将多个学生添加到列表中?
      • 创建更多学生对象student1 = new Student(21, "Alvin", "CSE", "07227832342");
      • 有没有办法使用循环来实现它?
      • 我用如何阅读多个用户并将他们添加到课程中的示例更新了答案。根据我为学生姓名编写的示例,我留下了一些代码供您自己填写
      • 收到错误提示找不到符号变量 student。
      猜你喜欢
      • 1970-01-01
      • 2017-10-19
      • 2019-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-12
      • 2012-02-06
      相关资源
      最近更新 更多