简体   繁体   中英

How to calculate the average in OOP?

I know how to calculate the average in procedural programming, except that in OOP I don't see how to make this:

I have 2 objects and I want to calculate the average age:

class Main {
  public static void main(String[] args) {
    List<Player> players = new ArrayList<Player>();

    players.add(new Player("Eric", 31, true));
    players.add(new Player("Juliette", 28, false));

In my class Player, I have this

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

In my CalculateAverage() method, I don't see how to make this? I have a problem with my loop..

public static void CalculateAverage(List <Player> players){
    int sumAge =  0;

    for(Player player : players){
            
    }
  } 

Method 1:

inside your loop sum all the ages and then divide the sum by total number of ages( players.size() )

 List<Player> players = new ArrayList<Player>();

    players.add(new Player("Eric", 31, true));
    players.add(new Player("Juliette", 28, false));
    double sum = 0;
    for(Player player : players){
        sum = sum +player.age;
    }
    double average = sum/players.size();
    System.out.println(average);
   

Method 2:

make use of Java 8 Streams. Convert your list to a stream( players.stream() ) then map your age to double( mapToDouble() ) then call average.

*NB average() returns an optional. use get( optionalAverage.get() ) to get the actual value.

 List<Player> players = new ArrayList<Player>();
    players.add(new Player("Eric", 31, true));
    players.add(new Player("Juliette", 28, false));
    final OptionalDouble optionalAverage = players.stream().mapToInt(Player::getAge).average();
    System.out.println(optionalAverage);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM