有没有办法可以根据团队所拥有的分数来排序我的团队arraylist,所以无论哪个团队得分最高,依此类推,请不要使用comperator,因为我不明白如何使用它,这是我的代码:
import java.util.*;
import java.io.*;
class team {
public int teamNum;
public int points = 0;
public team(int x) {
this.teamNum = x;
}
public team(int x,int y) {
this.teamNum = x;
this.points = y;
}
}
public class Problem9 {
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(new File("Test9.txt"));
ArrayList<team> teams = new ArrayList<>();
int counter=0;
while(in.hasNextLine()) {
boolean found = false;
String[] split = in.nextLine().split(" ");
int n1 = Integer.parseInt(split[0]);
int n2 = Integer.parseInt(split[1]);
if (!(n1 == 0 && n2 == 0)) {
if (counter<1) teams.add(new team(n1));
for (int i=0; i<teams.size(); i++) {
if (teams.get(i).teamNum == n1) {
teams.get(i).points+=n2;
found = true;
}
}
if (!found) {
teams.add(new team(n1, n2));
}
}
counter++;
}
for (int k=0; k<teams.size(); k++)
System.out.println(teams.get(k).teamNum + " " + teams.get(k).points);
}
}
答案 0 :(得分:2)
有两种方法可以对自定义数据类型进行排序:
使用可比较
end1='/home/.../file1.txt'
end2='/home/.../file2.txt'
with open(end1, "rb") as inf:
with open(end2, "w") as fixed:
for line in inf:
line = line.replace("\n", "")
line = line.replace("\r", "")
fixed.write(line)
现在在class team implements Comparable<team> {
public int teamNum;
public int points = 0;
public team(int x) {
this.teamNum = x;
}
public team(int x,int y) {
this.teamNum = x;
this.points = y;
}
public int compareTo(team t1){
return t1.points - this.points;
}
}
上使用Collections.sort()
,这会为您排序。
答案 1 :(得分:1)
同意@sschale,你不能仅仅因为你不知道如何使用它而因此不想使用它而逃避某些方法或库。为了帮助你,我将在这里给你一个简化的比较器实现形式:
//Place this between class team and public class Problem9
static class rankcomparator implements Comparator<Team> {
@Override //need to override
public int compare(Team lhs, Team rhs) {
return -compare(lhs.points, rhs.points); //if descending order
//return compare(lhs.points, rhs.points); //if ascending order
}
}
public static void main(String[] args) throws IOException {
//Add this code inside public class Problem9 ...
Collections.sort(teams, new rankcomparator());
}
答案 2 :(得分:1)
您确实需要了解Comparable
和getScore
界面的工作原理。我建议this tutorial on Comparator
usage和this tutorial on using natural ordering through the Comparable
interface。
关于手头的问题:只需在您的Team
课程中添加int getScore(){ return this.score;}
方法:
teams.sort(Comparator.comparing(Team::getScore));
然后致电:
teams.sort(Comparator.comparing(Team::getScore).reversed());
您可以使用以下方式撤销订单:
team
最后一件事:类名以大写字母开头是惯例。您应该将Team
课程重构为window.onload=function(){
var Nav=document.getElementById(window.location.href.split('/').pop().split('.')[0]);
if(Nav){
Nav.setAttribute('class','active');
}}
。
答案 3 :(得分:0)
您也可以在没有比较器的情况下执行此操作,因为您只有整数可以相互比较:
teams.sort((Team t1, Team t2) -> (Integer.compare(t1.getScore(), t2.getScore())));
Collections.reverse(teams);