It works and everything, but it looks horrible. All we’re given to draw data from is a text file with the data on hockey players. We then take this data and create players from it. Then make a list of these players. At no point are we given each team’s amount of wins, so I’m almost wondering if this is the best you can do.
Basically, what it wants to accomplish is to find the team with the most wins. This is found by the winning goals of each player being totalled, and judging by which team they were from, counting it for that team.
I accomplished this by creating the list of teams as Team objects by going through all the players and finding unique team names.
I then went through the player list and if the player’s team was equal to the current team being looked at, it would give them points for the winning goals.
Then, in yet another for loop, find the team with the highest amount of these goals.
Return this team.
That’s a total of four for loops for one little task. It seems gross.
/**
* 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;
}
As Jordan Denison pointed out in the comments, you can used a for-each loop. See below for an example.
In addition, currently you will only get the last team which has more wins than the first team. In order to get the team with the most wins you have to update the most wins:
Update
In addition, consider using a map as shown in the other answers.