Having trouble referring to a method in another class

Brian :

I'm almost completely new to Java and programming in general (my main degree is in Law but I'm hoping to open myself up to programming as I truly believe it's going to be an essential skill in a couple years).

I've created two classes, LabClass and Student, and the point is to enroll students into the class, while giving them credits for enrolling.

Here's the method in my Student class that I'm trying to access:

public void addCredits(int additionalPoints)
{
    credits += additionalPoints;
}

And here's the method in my LabClass class that I'm trying to use:

public void enrollStudent(Student newStudent)
{
    if(students.size() == capacity) {
        System.out.println("The class is full, you cannot enrol.");
    }
    else {
        students.add(newStudent);
    }
    students.addCredits(50);
}

What I don't understand is why BlueJ says that it cannot find the method "addCredits". I'm a real beginner so I'm sorry if this is a stupid question, but any help would be much appreciated!

Kovalainen :

You never show what the variable students is. However it seems to be an array of Students. You're invoking addCredits on an array of Students, instead of on the variable newStudent, which is what I suppose you want to do. The correct way of doing this would be:

public void enrollStudent(Student newStudent)
{
    if(students.size() == capacity) {
        System.out.println("The class is full, you cannot enrol.");
    }
    else {
        newStudent.addCredits(50);
        students.add(newStudent);
    }

}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=474072&siteId=1