gpt4 book ai didi

java 按成绩、名称对成绩进行排序

转载 作者:太空宇宙 更新时间:2023-11-04 10:24:53 24 4
gpt4 key购买 nike

此代码的结果是将 mergedGrades 移动到一个 SortedGrades 中,该 SortedGrades 基于按成绩排序,然后按名称排序。我设法找到从最高到最低的成绩,但我无法按名称对成绩进行排序。请帮忙。

我的代码:

        public static Grades sort(Grades mergedGrades, Grades repeat) {
Grades sortedGrades = new Grades();
while( (mergedGrades.size() > 0)){
Grade highComp = null;
Grade highest = mergedGrades.get(0);

int index = 0;
for (int j = 0; j < mergedGrades.size(); j++) {
highComp = mergedGrades.get(j);
if (highComp.getGpa() > highest.getGpa()) {
highest = highComp;
}
}
//sortedGrades.add(highest);

for(int i = 0 ; i < mergedGrades.size(); i++){
for (int i = 0; i < repeat.size(); i++) {
if (repeat.contains(highest)) {
if(highest.getFirstName().compareTo(repeat.get(i).getFirstName()) < 0) {
if(mergedGrades.get(i).getLastName().compareTo(highest.getLastName()) < 0) {
sortedGrades.add(highest);
System.out.println("test");
}
}
}
}
sortedGrades.add(highest);
mergedGrades.remove(index);

}

结果应该是这样的:

   S005: Stacy, Lu 4.0
S004: Aseef, Hernandez 3.9
S006: Aseef, Nilkund 3.9
S002: Jim, NLN 3.9
S003: Misty, Fang 3.9
S009: Steve, Calderon 3.9
S016: Aseef, Simmons 3.9
S010: Raj, Singh 3.8
S018: Hamza, Nilkund 3.5
S012: Kathy, Calderon 3.5
S017: Hifza, Nilkund 3.3
S011: Jason, Kramer 3.3
S001: John, Rodgers 3.3
S019: Chris, Peach 3.2
S013: Roopa, Singh 3.2
S020: Ramona, Luke 2.4
S014: Amid, Naveed 2.4
S015: Faith, Williams 1.0

最佳答案

比较 hashCode() 值并不是对名称进行排序的方法。使用 compareTo() 代替:

if (mergedGrades.get(i).getFirstName().compareTo(
highest.getFirstName()) < 0) {
// mergedGrades firstname < highest firstname
}

关于java 按成绩、名称对成绩进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50661774/

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