Skip to content
Advertisement

How Can I calculate the difference of age between 2 objects?

I am learning JAVA OOP, I have to compare the age between 2 objects:

In java Procedural, I will have done:

public static int calculateDifferenceAge(int agePlayer1, int agePlayer2){
      int differenceAge = agePlayer1 - agePlayer2;

      if(differenceAge < 0){
        differenceAge = -differenceAge;
      }
      return differenceAge; 
}

Then

public static void displayDifferenceAge(String namePlayer1, String namePlayer2, int agePlayer1, int agePlayer2){
      System.out.println("Age difference between " + namePlayer1 + " and " + namePlayer2 + " is of" + calculateDifferenceAge(agePlayer1, agePlayer2) + " year(s).");
    }
}

I don’t understand how to create my calculateDifferenceAge() method in OOP ?

In my main file I have this:

List<Player> players = new ArrayList <Player>();
players.add(new Player("Eric", 31, true));
players.add(new Player("Juliette", 27, false));

I am stuck into my 2 methods:

How to subtract the age of 2 objects?

public static int calculateAgeDifference(List <Player> players){

    Player differenceAge = (players.get(0) - players.get(1));

    return differenceAge; 

  }

  public static void displayCalculateAgeDifference(List <Player> players){
    System.out.println(calculateAgeDifference().age);
  }

Class Player

public class Player {

  public String name;
  public int age;
  public boolean sex;

  public Player(String name, int age, boolean sex){
    this.name = name;
    this.age = age;
    this.sex = sex;
  }

Advertisement

Answer

you’re only missing a little step in your code. The steps to extract the ages of the list should be:

1.- Extract the object from the list

2.- Extract the age of that object (or player, in this case)

3.- Substract the ages

There’s some ways to do it, but I would do it this way:

public static int calculateAgeDifference(List<Player> players) {
    int age1= players.get(0).age;
    int age2= players.get(1).age;

    int differenceAge = age1 - age2;

    if(differenceAge < 0){
        differenceAge = -differenceAge;
    }
    return differenceAge;
}

I hope that helps. What i’ve done there is extract the objects player from the list: players.get(0) extracts the first object inside the list, which is a Player. Now that I have a player and it has an age variable i have to extract it with player.age. I collapsed those steps, if you have any questions I can explain you further

Display method:

 public static int displayCalculateAgeDifference (List<Player> players){
    String name1= players.get(0).name;
    String name2= players.get(1).name;
    
    //as you know this method return the difference in a number form
    int difference= calculateAgeDifference(players);

    System.out.println("Age difference between " + name1 + " and " + name2 + " is of" + difference + " year(s).");
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement