Home > database >  Find highest age of person in Array and return name
Find highest age of person in Array and return name

Time:01-04

Task: your task is to expand the class PersonRegister through coding the method nameOftheOldest(). The methods task is to find and return the name of the person that is the oldest in the register (that is the oldest of those stored in the list allPersons array).

Code of the class looks like this:

public class PersonRegister
{
    // instance variables - replace the example below with your own
    private Person[] allPersons;

    /**
     * Constructor for objects of class PersonRegister
     */
    public PersonRegister(int numberOfPersons)
    {
        // initialise instance variables
        this.allPersons = new Person[numberOfPersons];
    }
    
    public void registreraPerson(int index, Person aPerson)
    {
        
        allPersons[index] = aPerson;
        
    }
}

There is another class called Person in the program that looks like this:

public class Person
{
    // instance variables - replace the example below with your own
    private String name;
    private int birthYear;

    /**
     * Constructor for objects of class ExperimentJavaLoops
     */
    public Person(String name, int birthYear)
    {
        // initialise instance variables
        this.name = name;
        this.birthYear = birthYear;
    }
    
    public String getName()
    {
        return name;
        
    }
    
    public int birthYear()
    {
        return birthYear;
    }
    
    public void setName(String name)
    {
        this.name = name;
        
    }
    
    public void setbirthYear(int birthYear)
    {
        
        this.birthYear = birthYear;
        
    }
}

Googled this a lot, read literature and tried to code it but cant find a solution. I think I'm supposed to loop through the array and compare values inside the loop through an if-statement. Then also use external method calls to get the name and birthyear (oldest will be the person with lowest birthyear, naturally). And it should be converted to String and returned in order to return name? Confused. Very new to programming and a bit more used to ArrayLists than Arrays.

CodePudding user response:

Or you could use a stream approach:

    Optional<Person> eldest = Arrays.stream(allPersons)
        .collect(Collectors.maxBy((p1, p2) -> Integer.compare(p1.getAge(), p2.getAge())));
    System.out.println("Eldest is "   eldest.get());

But you might want to do a simple iteration, keeping track of the current oldest, as has been suggested

CodePudding user response:

This should get you started.

public String nameOfTheOldest()
{
    Person oldest = allPersons[0];
    for (int i = 1; i < allPersons.length; i  )
    {
        if (allPersons[i] ...)
            ...
    }
    return ...;
}
  • Related