-2

public Person getOldest(Person personA, Person personB, Person personC) {

A method passes in 3 parameters of object Person in which Person can use the getAge() method. I'm trying to find the oldest person but some of them may be null in which case will return the oldest person that isn't null. If all three are null then it will return null.

I thought of using a bunch of nested if, else if loops to go through every combination of null and getAge() to find the oldest Person but there has to be a better method.

NoobCoder
  • 5
  • 1
  • Typically, you would have a single parameter that’s an array of Person s. Then you can do something like : Person highestAgePerson = null; int highestAge = 0; for(Person person in personArray) if(person and person.getAge() > highestAge) { highestAgePerson = person; highestAge = person.getAge(); } – George Jan 21 '23 at 23:19

1 Answers1

2

You can make another method called getOldest(p1, p2) with only 2 parameters and then do the following:

Person getOldest(p1, p2) {
    if (p1 == null && p2 == null) { return null; }
    if (p1 == null) { return p2; }
    if (p2 == null) { return p1; }
    if ( p1.getAge() > p2.getAge() ) { return p1; } else { return p2; }
}

Person getOldest(p1, p2, p3) { return getOldest(p1, getOldest(p2, p3)); }

Sorry for the formatting, I'm on a phone.

Majiick
  • 233
  • 1
  • 13
  • But as George said, it might be easier to just put it all into a list, filter out all of the null persons and then get the max value for age: https://stackoverflow.com/questions/19338686/getting-max-value-from-an-arraylist-of-objects – Majiick Jan 21 '23 at 23:21