我得到了一个对象列表,每个对象都具有int
类型的属性。如何在列表中的所有对象上找到此属性的最大值和最小值?
public class app
{
public static void main(String[] args)
{
// professor p = new professor("Name", "LName", "Degree", Age);
professor p0= new professor("Chad", "Froes", "Biochemistry", 21);
professor p1= new professor("Chad", "Froes", "Biochemistry", 21);
professor p2 = new professor("Carol", "Hammond", "Modern Art", 43);
//Oldest professor
if (p0.ageGV > p1.ageGV && p0.ageGV > p2.ageGV)
{
System.out.println(p0.getOldest());
}
else if (p1.ageGV > p0.ageGV && p1.ageGV > p2.ageGV)
{
System.out.println(p1.getOldest());
}
else if (p2.ageGV > p1.ageGV && p2.ageGV > p0.ageGV)
{
System.out.println(p2.getOldest());
}
System.out.println("\n");
//Youngest sort
if (p0.ageGV < p1.ageGV && p0.ageGV < p2.ageGV)
{
System.out.println(p0.getYoungest());
}
if (p1.ageGV < p0.ageGV && p1.ageGV < p2.ageGV)
{
System.out.println(p1.getYoungest());
}
if (p2.ageGV < p1.ageGV && p2.ageGV < p0.ageGV)
{
System.out.println(p2.getYoungest());
}
}
}
答案 0 :(得分:0)
您可以尝试这样的事情:
Professor maxAge = null;
Professor minAge = null;
for(Professor p : new Professor[] {p0, p1, p2}) {
if(maxAge == null || maxAge.age < p.age) {
maxAge = p;
}
if(minAge == null || minAge.age > p.age) {
minAge = p;
}
}
System.out.println("Maximum age: " + maxAge.firstName + " " + maxAge.lastName);
System.out.println("Miminum age: " + minAge.firstName + " " + minAge.lastName);
我建议您将变量重命名为convention。