2017-02-21 6 views
-4

Im пытается создать студенческого arraylist в классе курса, чтобы при добавлении ученика аррайалист увеличивается. это код, который у меня до сих пор:Создание студенческого arraylist для добавления учеников в класс курса Java

import java.util.ArrayList; 

/* 
* To change this license header, choose License Headers in Project Properties. 
* To change this template file, choose Tools | Templates 
* and open the template in the editor. 
*/ 

/** 
* 
* @author Saj 
*/ 
public class Course { 
    private String courseName; 
    private int noOfStudents; 
    private String teacher; 
    public static int instances = 0; 

    //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(){ 
     instances++; 
     this.noOfStudents = 0; 
     this.courseName = "Not Set"; 
     this.teacher = "Not Set"; 
    } 

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

} 

Im unsure, как реализовать список массивов. Может кто-то указать мне в правильном направлении.

+0

«Im уверены, как реализовать список массива.» Вы не реализуете ArrayList. Это встроенная коллекция. Объявите его следующим образом: «Список students = new ArrayList ();'. Это предполагает, что вы действительно создали класс Student. – Arqan

+3

Вы читали документацию и/или смотрели какие-либо руководства/руководства о 'ArrayList'? – tnw

+0

@ Аркан, где я объявляю это? – donk2017

ответ

0

Просто добавьте атрибут к классу

List<Student> students; 

В конструкторах, инициализировать этот список:

students = new ArrayList<>(); 

Создать метод добавления студента в список:

public boolean addStudent(Student stud) { 
    if (stud == null || students.contains(stud)) { 
     return false; 
    } 
    students.add(stud); 
    return true; 
} 

проверить Также https://docs.oracle.com/javase/8/docs/api/java/util/List.html для документация списка. Вопрос: вы хотите добавить студентов в конструктор? Если это так, добавьте параметр в конструкторе

public Course(int noOfStudents, String courseName, 
       String teacher, List<Student> students){ 
    this.noOfStudents = noOfStudents; 
    this.courseName = courseName; 
    this.teacher = teacher; 
    this.students = new Arraylist<>(students); 
} 
+0

См. Ответ, который я опубликовал с измененным кодом, но я получаю сообщение об ошибке. – donk2017

+0

Какая ошибка у вас? И где вы указали атрибут List ? добавить сразу после 'публичных статических ИНТ экземпляров = 0;' просто введите частные 'Список студентов,' + Один совет, не используйте 'ArrayList studentList = новый ArrayList ();' использование 'List studentList = new ArrayList ();' вместо – Nayriva

1

С немного исследований вы можете найти много учебников, чтобы добиться того, что вы собираетесь, но я буду пытаться установить вас в правильном пути, просто так у вас есть answear и где-то начать.

  1. Что является студентом? Является ли это строкой, содержащей только имя, является ли это объектом, представляющим ученика, который может иметь некоторые свойства? Одним из примеров является

    public class Student{ 
        private int number; 
        private String name; 
        private int age; 
        // Basically anything that makes sense for a student. 
    
        public Student(int number, String name, int age){ 
         this.number = number; 
         this.name = name; 
         this.age = age; 
        } 
    
        // .... Getters and Setters. 
    } 
    
  2. Вам нужно какое-то место для хранения каждый студент добавлен в курсе, что это то, что ArrayList для т.е.

    List<Student> students = new ArrayList<Student>(); 
    Student foo = new Student(23, "Foo", 22); 
    students.add(foo); // This is how you add to a List (in this case a List of Student objects and more precisely an ArrayList of Students). 
    

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

Если у вас есть больше сомнений, сначала найдите решение, прежде чем задавать вопросы, которые легко найти. Вот некоторые ссылки:

Java List

Java ArrayList

EDIT путь вы добавляете ваши студенты почти сделано, но у вас есть ошибки, а также ваш список студентов проживает только внутри конструктора, что означает, что вы не можете использовать список для сохранения студентов на улице.

Ниже приведен корректный код

/** 
* Constructor with parameters 
* @param noOfStudents integer 
* @param courseName String with the Course name 
* @param teacher String with the teacher 
*/ 
public Course(int noOfStudents, String courseName, String teacher){ 
    this.studentList = new ArrayList<Student>(); // The declaration is in above in your class, as an instance variable. 
    this.courseName = courseName; 
    this.teacher = teacher; 
} 
ArrayList<Student> studentList; // You can move this so it sits above besides your other variables, but it will also work like this. 
public boolean addStudent(Student student){ 
    if (student==null || studentList.contains(student)) { // You had Student.contains, wich will give an error because Student (class) doesnt have a static method named contains. 
     return false; 
    } 
    studentList.add(student); // you had the same problem here, you had Student.add(student), wich is wrong and it would not compile. 
    return true; 
} 

Убедитесь, что вы создали класс Student и это без каких-либо ошибок.

Испытано и рабочий код, изменить его FULLFILL ваши потребности более точно

import java.util.ArrayList; 


public class Course { 
    private String courseName; 
    private int noOfStudents; 
    private String teacher; 
    public static int instances = 0; 
private ArrayList<Student> studentList; 

    //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(){ 
     instances++; 
     this.noOfStudents = 0; 
     this.courseName = "Not Set"; 
     this.teacher = "Not Set"; 
    } 

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

    public boolean addStudent(Student student){ 
     if (student==null || studentList.contains(student)) { 
      return false; 
     } 
     studentList.add(student); 
     return true; 
    } 

    public void printStudents(){ 
    for(Student s : studentList) 
      System.out.println(s.getName() + ", with " + s.getAge() + " year(s)"); 
    } 

public static class Student{ 
     private int number; 
     private String name; 
     private int age; 
     // Basically anything that makes sense for a student. 

     public Student(int number, String name, int age){ 
      this.number = number; 
      this.name = name; 
      this.age = age; 
     } 

     // .... Getters and Setters. 

     public int getNumber(){ 
      return this.number; 
     } 

     public String getName(){ 
      return this.name; 
     } 

     public int getAge(){ 
      return this.age; 
     } 
} 
    // Testing code 
    public static void main(String[] args){ 
     Course oop = new Course(6, "Object Oriented Programming", "LeBron James"); 
     oop.addStudent(new Course.Student(6, "Michael Jordan", 56)); 
     oop.addStudent(new Course.Student(23, "Kyrie Irving", 24)); 
     oop.addStudent(new Course.Student(14, "Kevin Love", 27)); 
     System.out.println(oop.getCourseName() + " has the following students"); 
     oop.printStudents(); 

    } 

} 
+0

См. Ответ, который я опубликовал с измененным кодом, но я получаю сообщение об ошибке. – donk2017

+0

@ donk2017 См. Мое редактирование, я исправил некоторые вещи с помощью вашего кода, у вас были серьезные проблемы с ним. –

+0

Мне нужно использовать toString, а затем сделать 'System.out.println (course.toString());' и 'System.out.println (student.toString());' из основного класса, чтобы распечатать курс и студенческая информация. Кроме того, я должен вводить данные о студенте с терминала при запуске кода. – donk2017

Смежные вопросы