-2

I got a list of objects each having an attribute of type int. How do I find the max and min values of this attribute over all the objects in the list?

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());
     }

    }   
}
Jeshurun
  • 22,940
  • 6
  • 79
  • 92
Ross P.
  • 21
  • 1
  • 1
  • 3
  • 3
    You must show effort in researching, posting the code you have tried, explaining why it didn't work, and asking an specific question. Also post a [Minimal, Complete, Tested and Readable example](http://stackoverflow.com/help/mcve) so it's easier for us to help you. – Christian Tapia Jan 19 '14 at 21:17
  • I have tried multiple if statements and the first if statement with the minimum values is the only one that executes. But I need an additional if statement to execute as well with the max value. – Ross P. Jan 19 '14 at 21:23
  • @user235028 Show your code and people will vote to reopen this question. – Alexis C. Jan 19 '14 at 21:23
  • I want to execute two different searches of the information that I have stored in the registries with two different if statements for greatest value and smallest value of attribute ageGV. – Ross P. Jan 19 '14 at 21:27

1 Answers1

0

You could try something like this:

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);

I would suggest renaming your variables to follow convention.

Jeshurun
  • 22,940
  • 6
  • 79
  • 92