С немного исследований вы можете найти много учебников, чтобы добиться того, что вы собираетесь, но я буду пытаться установить вас в правильном пути, просто так у вас есть answear и где-то начать.
Что является студентом? Является ли это строкой, содержащей только имя, является ли это объектом, представляющим ученика, который может иметь некоторые свойства? Одним из примеров является
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.
}
Вам нужно какое-то место для хранения каждый студент добавлен в курсе, что это то, что 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();
}
}
«Im уверены, как реализовать список массива.» Вы не реализуете ArrayList. Это встроенная коллекция. Объявите его следующим образом: «Список students = new ArrayList ();'. Это предполагает, что вы действительно создали класс Student. –
Arqan
Вы читали документацию и/или смотрели какие-либо руководства/руководства о 'ArrayList'? – tnw
@ Аркан, где я объявляю это? – donk2017