我正在尝试获取最长名字的长度并将其保存为最长的,但我的代码无法从我的班级中正确获取名字
这是我的代码:
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;
}
以下是我获取变量的地方:
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 :(得分:3)
getFirstName
不是变量,它是一种方法。调用方法时,Java语法需要括号(即使方法不带参数):
if (studentList.get(i).getFirstName().length() > longest);
^^
(并在下一行)。
顺便说一下,您可以用:
替换整个if
构造
longest = Math.max(studentList.get(i).getFirstName().length(), longest);
为了进一步简化这一点,您可以使用for-each循环:
public static int findLongestFirstName(ArrayList<Student> studentList)
{
int longest = 0;
for (Student student : studentList) {
longest = Math.max(student.getFirstName().length(), longest);
}
return longest;
}
答案 1 :(得分:1)
您的代码似乎很好,但是在if语句的末尾有一个半冒号导致了这个问题。