gpt4 book ai didi

java - 如何返回对象 ArrayList 中的总和

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:09:24 24 4
gpt4 key购买 nike

对每个循环使用一个。我如何计算每个玩家的进球数并将其返回到 Team 类中的方法 goals() 中?我知道我当前的返回声明是错误的,我不确定该放什么:

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

最佳答案

我想你正在寻找类似的东西

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

将每个Player的进球数加到总数中,然后返回total

关于java - 如何返回对象 ArrayList 中的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27808525/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com