简体   繁体   中英

Having trouble referring to a method in another class

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!

Students is an ArrayList or something... not a student. I think maybe you mean to say newStudent.addCredits(50);

You never show what the variable students is. However it seems to be an array of Student s. 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);
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM