1

I am trying to get the length of the longest first name and saving it as int longest, but my code is not properly fetching the first names from my class Student

here is my code:

public static int findLongestFirstName(ArrayList<Student> studentList) 
{
    int longest = 0;
    for (int i = 0; i < studentList.size(); i++)
        {
            if (studentList.get(i).getFirstName.length() > longest);
            {
                longest = studentList.get(i).getFirstName.length();
            }
        }
    return longest;
}

Here is where I am fetching my variables:

public class Student 
{
private int IDnum;
private String firstName;
private String lastName;
private int gradYear;
private double gradePoint;
public Student(int ID, String first, String last, int year, double GPA)
{
    IDnum = ID;
    firstName = first;
    lastName = last;
    gradYear = year;
    gradePoint = GPA;
}
public int getID()
{
    return IDnum;
}
public String getFirstName()
{
    return firstName;
}
public String getLastName()
{
    return lastName;
}
public int getYear()
{
    return gradYear;
}
public double getGPA()
{
    return gradePoint;
}

}

0

2 Answers 2

3

getFirstName is not a variable, it's a method. Java syntax requires parentheses when calling a method (even if the method takes no arguments):

if (studentList.get(i).getFirstName().length() > longest);
                                   ^^

(and on the next line).

By the way, you can replace the entire if construct with:

longest = Math.max(studentList.get(i).getFirstName().length(), longest);

To simplify this further, you could use a for-each loop:

public static int findLongestFirstName(ArrayList<Student> studentList) 
{
    int longest = 0;
    for (Student student : studentList) {
        longest = Math.max(student.getFirstName().length(), longest);
    }
    return longest;
}
Sign up to request clarification or add additional context in comments.

Comments

1

Your code seems fine however there is a semi colon at the end of your if statement which is causing the issue.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.