【问题描述】
对某班学生成绩排序。从键盘依次输入某班学生的姓名和成绩(一个班级人数最多不超过50人)并保存,然后分别按学生成绩由高到低顺序输出学生姓名和成绩,成绩相同时,则按输入次序排序。
【输入形式】
从键盘依次输入最多不超过50个学生的学生姓名和成绩:
第一行输入班级学生人数;
在单独行上输入空格隔开的学生姓名和成绩,其中学生成绩是整数。
【输出形式】
按学生成绩由高到低顺序输出学生姓名和成绩,每行输出一位学生的姓名和成绩,其中姓名(英文)占15位,成绩占5位,均按缺省方式对齐。成绩相同时按输入次序排序。
【输入样例】
4
aaa 50
bbb 70
ccc 65
ddd 90
【输出样例】
############ddd###90
############bbb###70
############ccc###65
############aaa###50
(注意:其中“#”号代表空格)
【样例说明】输入了四个学生姓名和成绩,按成绩排序输出。
参考代码一:(使用Map集合)
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class student {
public static <K, V extends Comparable<? super V>> Map<K, V> sortDescend(Map<K, V> map) {
List<Map.Entry<K, V>> list = new ArrayList<>(map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
@Override
public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
int compare = (o1.getValue()).compareTo(o2.getValue());
return -compare;
}
});
Map<K, V> returnMap = new LinkedHashMap<K, V>();
for (Map.Entry<K, V> entry : list) {
returnMap.put(entry.getKey(), entry.getValue());
}
return returnMap;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Map<String,Integer> student = new HashMap<String,Integer>();
int n = sc.nextInt();
while(n-->0) {
String name = sc.next();
int score = sc.nextInt();
student.put(name, score);
}
student = sortDescend(student);
for(String u:student.keySet()) {
System.out.printf("%15s%5d\n",u,student.get(u));
}
sc.close();
}
}
参考代码二:
import java.util.*;
public class student {
private String name;
private int score;
public student(String name,int score) {
this.name=name;
this.score=score;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
student s = null;
List<student> stu = new ArrayList<student>();
for(int i=0;i<n;i++) {
String s_name = sc.next();
int d = sc.nextInt();
s = new student(s_name,d);
stu.add(s);
}
//冒泡排序法
for(int i=0;i<n;i++) {
for(int j=0;j<n-i-1;j++) {
if(stu.get(j).score<stu.get(j+1).score) {
int temp = stu.get(j).score;
String ssx = stu.get(j).name;
stu.get(j).score = stu.get(j+1).score;
stu.get(j).name = stu.get(j+1).name;
stu.get(j+1).score = temp;
stu.get(j+1).name = ssx;
}
}
}
for(student f:stu) {
System.out.printf("%15s%5d\n", f.name, f.score);
}
}
}
编程小白,大佬勿喷,有错请指出,谢谢!