Reputation: 109
Using a for each loop. how can I count the number of goals each player has and return that in the method goals()
which is in the Team
class? I know my current return statement is wrong I was unsure 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());
}
}
Upvotes: 3
Views: 1747
Reputation: 201429
I think you're 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 number of each Player
's goals to the total and then return the total
.
Upvotes: 3
Reputation: 311163
Just accumulate them in a temporary variable:
public int goals() {
int goals = 0;
for(Player p : list){
goals += p.goals();
}
return goals;
}
Upvotes: 2