How to return the sum to an ArrayList object

Using a for each loop. how can I count the number of goals each player has and return them in the method goals()

that is in the class Team

? I know my current return statement is wrong. I didn't know what to put there:

import java.util.ArrayList;

public class Team {

    private String teamName;
    private ArrayList<Player> list;
    private int maxSize = 16;

    public Team(String teamName) {
        this.teamName = teamName;
        this.list = new ArrayList<Player>();
    }

    public String getName() {

        return this.teamName;
    }

    public void addPlayer(Player player) {

        if (list.size() < this.maxSize) {
            this.list.add(player);
        }

    }

    public void printPlayers() {
        System.out.println(list);
    }

    public void setMaxSize(int maxSize) {

        this.maxSize = maxSize;
    }

    public int size() {

        return list.size();
    }

    public int goals(){

        for(Player goals : list){

        }
        return list;
    }
}

      


public class Player {

    private String playerName;
    private int goals;

    public Player(String playerName) {

        this.playerName = playerName;
    }

    public Player(String playerName, int goals) {

        this.playerName = playerName;
        this.goals = goals;
    }

    public String getName() {

        return this.playerName;
    }

    public int goals() {

        return this.goals;
    }

    public String toString() {

        return "Player: " + this.playerName + "," + goals;
    }
}

      


public class Main {
    public static void main(String[] args) {
        // test your code here
        Team barcelona = new Team("FC Barcelona");

        Player brian = new Player("Brian");
        Player pekka = new Player("Pekka", 39);
        barcelona.addPlayer(brian);
        barcelona.addPlayer(pekka);
        barcelona.addPlayer(new Player("Mikael", 1)); // works similarly as the above

        System.out.println("Total goals: " + barcelona.goals());
    }
}

      

+3


source to share


3 answers


I think you are looking for something like

public int goals(){
    int total = 0;
    for(Player p : list){ // for each Player p in list         
       total += p.goals();
    }       
    return total;
}

      



Add the count of all goals Player

to the total and then return total

.

+3


source


return list.stream().mapToInt(Player::goals).sum();

      



+3


source


Just copy them into a temporary variable:

public int goals() {
    int goals = 0;
    for(Player p : list){
        goals += p.goals();
    }       
    return goals;
}

      

+2


source







All Articles