2017-02-21 17 views
-2

Im пытается создать класс ученика, класс курса и основной класс. Я пытаюсь добавить студентов на курс, и когда ученики добавляются в класс, количество студентов в курсе должно увеличиваться, когда код запускается, он должен печатать данные курса, за которыми следуют учащиеся курса.Как добавить нескольких учеников в класс учеников?

Я получил следующий код: Основного класса:

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; 
    } 
} 

класс Student:

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; 
    } 
} 
+1

так Курс имеет метод addStudent. что может показаться полезным здесь – MeBigFatGuy

+0

@MeBigFatGuy Я не понимаю? – anon1234

+0

'public static void addStudent (Student newStudent)' этот метод не должен быть статическим! –

ответ

0

Поскольку вы инициализируетесь список массива в Класс курса, вы должны добавить студентов к нему. Вы должны создать метод в курсе, который добавляет объект в список массива, такие как:

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 метод сделал для вас в списке массивов.

+3

к счастью, этот метод уже существует – MeBigFatGuy

+0

Но как бы я добавил несколько учеников? – anon1234

+0

@ anon1234 вы можете передать массив учеников в качестве аргумента и добавить каждого ученика в список. Переход к обновлению ответа через секунду. – hallaksec

0
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(); 
} 

}

я переделывал немного ваш метод ToString() из класса Course. Это должно распечатать список студентов, посещающих класс.

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; 
} 
+0

Но как бы добавить в список несколько учеников? – anon1234

+0

создать еще студенческие объекты 'student1 = new Student (21,« Alvin »,« CSE »,« 07227832342 »);' – Sitram

+0

Есть ли способ реализовать его с помощью цикла? – anon1234

0
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; 
    } 
} 
Смежные вопросы