【发布时间】:2012-09-29 04:09:51
【问题描述】:
一切正常,但看起来很糟糕。我们只需要一个包含曲棍球运动员数据的文本文件来获取数据。然后我们获取这些数据并从中创建玩家。然后列出这些球员的名单。我们从来没有给每支球队的胜利数量,所以我几乎想知道这是否是你能做的最好的。
基本上,它想要完成的是找到获胜最多的团队。这是通过计算每个球员的获胜目标,并根据他们来自哪支球队来判断的,并为该球队计算。
我通过遍历所有玩家并找到唯一的团队名称将团队列表创建为团队对象来实现这一点。
然后我浏览了球员名单,如果球员所在的球队与当前球队相同,那么他们就会为获胜进球得分。
然后,在另一个 for 循环中,找到这些目标数量最多的团队。
返回这个团队。
对于一个小任务,总共有四个 for 循环。看起来很恶心。
/**
* Returns the team with the most wins
*/
public Team getTeamWithMostWins() {
Team teamWithMostWins = new Team();
List<Team> teams = new List<Team>();
if (!players.isEmpty()) {
// Compile the List of teams
for (int i = 0; i < players.size(); i++) {
if (!teams.contains(players.get(i).getTeam())) {
teams.add(new Team(players.get(i).getTeam()));
}
}
// Set the wins for the teams
for (int i = 0; i < players.size(); i++) {
String team = players.get(i).getTeam();
int winningGoals = players.get(i).getWinningGoals();
// Go through the teams List to set the points
for (int j = 0; j < teams.size(); j++) {
// If the current player's team is equal to the current team in the loop
if ((teams.get(j).getName()).equals(team)) {
teams.get(j).incrementWinsBy(winningGoals);
}
}
}
int mostWins = teams.get(0).getWins();
// Find the team with the most wins
for (int i = 1; i < teams.size(); i++) {
if (teams.get(i).getWins() > mostWins) {
teamWithMostWins = teams.get(i);
}
}
}
else {
teamWithMostWins = null;
}
return teamWithMostWins;
}
【问题讨论】:
-
好吧,如果你只是迭代一个集合,for-each 循环通常要容易得多:)leepoint.net/notes-java/flow/loops/foreach.html 举个例子
-
我不认为它看起来很糟糕。这是可以理解的,这远比外表或聪明更重要。
标签: java