好的,所以我在这里有点不知所措,但是这里有。因此我需要在打印出来时对阵列奖章进行排序。首先,我需要按照添加到索引[0]的金牌排序,在索引[1]中的银牌之后排名第二,在索引[2]中排在铜牌之后排名第三,如果团队被绑定则排在最后,他们按球队名称排序。我是否需要在另一个班级中调用排序方法,跟踪其中一个并进行排序并与其他团队进行比较,如果他们最好先打印出来?
如何比较一个类的数组中的整数?
当用户输入某个命令时,将打印出包含其结果的团队列表。
截至目前,它看起来像这样:
1st 2nd 3rd Team Name
0 0 0 North Korea
3 1 1 America
5 0 2 France
2 1 3 Germany
我想说:
1st 2nd 3rd Team Name
5 0 2 France
3 1 1 America
2 1 3 Germany
0 0 0 North Korea
import java.util.ArrayList;
import java.util.Arrays;
public class Team {
private String teamName;
private ArrayList<Participant> participantList = new ArrayList<Participant>();
private int[] medalList = new int[3];
public Team(String teamName) {
this.teamName = teamName;
}
public String getTeamName() {
return teamName;
}
public void addParticipant(Participant participant) {
participantList.add(participant);
}
public void removeFromTeam(int participantNr){
for(int i = 0; i < participantList.size(); i++){
if(participantList.get(i).getParticipantNr() == participantNr){
participantList.remove(i);
}
}
}
public void printOutParticipant() {
for(int i = 0; i < participantList.size(); i++){
System.out.println(participantList.get(i).getName() + " " + participantList.get(i).getLastName());
}
}
public boolean isEmpty() {
boolean empty = false;
if (participantList.size() == 0) {
empty = true;
return empty;
}
return empty;
}
public void emptyMedalList(){
Arrays.fill(medalList, 0);
}
public void recieveMedals(int medal) {
if(medal == 1){
int gold = 0;
gold = medalList[0];
medalList[0] = ++gold;
} else if (medal == 2){
int silver = 0;
silver = medalList[1];
medalList[1] = ++silver;
} else if (medal == 3){
int bronze = 0;
bronze = medalList[2];
medalList[2] = ++bronze;
}
}
public void printMedals(){
System.out.println(medalList[0] + " " + medalList[1] + " " + medalList[2] + " " + teamName);
}
public int compareTo(Team team) {
int goldDif = Integer.compare(team.medalList[0], this.medalList[0]);
if (goldDif != 0)
return goldDif;
int silverDif = Integer.compare(team.medalList[1], this.medalList[1]);
if (silverDif != 0)
return silverDif;
int bronzeDif = Integer.compare(team.medalList[2], this.medalList[2]);
if (bronzeDif != 0)
return bronzeDif;
return this.getTeamName().compareTo(team.getTeamName());
}
public String toString() {
return teamName;
}
}
答案 0 :(得分:1)
使您的团队课程具有可比性
public class Team implements Comparable<Team> {
并添加比较方法
@Override
public int compareTo(final Team other) {
for (int i = 0; i < 3; i++) {
final int compareMedals = Integer.compare(medalList[i], other.medalList[i])
if (compareMedals != 0) {
return compareMedals;
}
}
return teamName.compareTo(other.teamName);
}
这将首先检查金牌,然后如果金牌数量相等则获得银牌,并使用团队名称比较作为最后的手段。然后,您可以使用
对Team
s的集合进行排序
final List<Team> teams = new ArrayList<>();
...
Collections.sort(teams);
修改强>
或者如果您喜欢Java 8风格,您也可以编写比较方法,如
@Override
public int compareTo(final Team other) {
return Stream.of(0, 1, 2)
.map(i -> Integer.compare(medalList[i], other.medalList[i]))
.filter(i -> i != 0)
.findFirst()
.orElse(teamName.compareTo(other.teamName));
}