0
class Course {
    private String courseName;
    ArrayList<String> students = new ArrayList<>();
    private int numberOfStudents;

    public Course(String courseName) {
        this.courseName = courseName;
    }

    public void addStudent(String student) {
        students[numberOfStudents] = student;//<-- Line 15
        numberOfStudents++;
    }

    public ArrayList getStudents() {
        return students;
    }

    public int getNumberOfStudents() {
        return numberOfStudents;
    }

    public String getCourseName() {
        return courseName;
    }
}

Line 15 I am getting error "Array required, but ArrayList found.

I am unsure what to do here as I am new to strings and such.

4

2 回答 2

3

students被声明为ArrayList. 这个符号

students[numberOfStudents] = student;

仅适用于数组类型。你应该使用

students.add(student);

请阅读ArrayList的 javadoc 。

你也不需要保留一个字段来保存学生的数量,因为

students.size();

会给你的。

于 2013-08-31T16:33:11.270 回答
1

如果你想在你的程序中使用 ArrayList:

public void addStudent(String student) {
     students.add(student);
   }

 public int getNumberOfStudents() {
     return students.length();
   }  

那么你也不需要numberOfStudents变量

于 2013-08-31T16:37:41.757 回答