为每个循环使用a。我如何计算每个玩家拥有的目标数量,并在goals()
类中的Team
方法中返回该目标?我知道我目前的回复陈述是错误的我不确定该放什么:
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());
}
}
答案 0 :(得分:3)
我认为你正在寻找像
这样的东西public int goals(){
int total = 0;
for(Player p : list){ // for each Player p in list
total += p.goals();
}
return total;
}
将每个Player
目标的数量添加到总数中,然后返回total
。
答案 1 :(得分:3)
return list.stream().mapToInt(Player::goals).sum();
答案 2 :(得分:2)
只需将它们累积在一个临时变量中:
public int goals() {
int goals = 0;
for(Player p : list){
goals += p.goals();
}
return goals;
}