-2

I am trying to get age in years of objects (members of a club) I have constructed with a LocalDate DOB, but the age keeps returning as 0.

I have a method that calculates the time period between the objects date of birth and today, I then use the getYears method to change that into a long I can compare.

code in members class:

//Methods to work out age from DOB
}
public void setYearsAge(long years) {
    Period age = Period.between(this.getDateOfBirth(), today);
    years = age.getYears();
    this.years = years;
}
public long getYearsAge() {
    return years;
}

//method called from main

String memberInfoMaleOver() {
    if(gender.contains("Male") && getYearsAge() > 17) {
        return firstName;
    }
    else 
        return "Invalid";
    }

Calling from main:

    //ma = user input from earlier

    do {
         System.out.println(maleMember[j].memberInfoMaleOver());

            if (maleMember[j].memberInfoMaleOver()=="No more Male team members") 
                    break;
            else 
                    j++;

        } while (j != ma);
  • How is `today` defined? Are you sure `years = age.getYears();` sets the value of the correct variable? Can you show us the entire class? I don't really get why you are having a `void` method that gets a parameter and then redefines that parameter value... – deHaar Jan 06 '20 at 12:59
  • 2
    Do not compare strings using `==`. See https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java. – VGR Jan 06 '20 at 13:03

1 Answers1

0

Do following change

private void updateAge(){
    Period age = Period.between(this.getDateOfBirth(), today);
    this.years = age.getYears();
}  
public void setYearsAge(long years) {
     updateAge();
}
public long getYearsAge() {
  if(this.years ==0 )
{
      updateAge();
}
    return this.years;
}
divyang4481
  • 1,584
  • 16
  • 32