import java.util.*; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); String s = null; HashMap<String, Student> Sites = new HashMap<String, Student>(); while (!"end".equals(s)){ s = input.nextLine(); if (!"end".equals(s)){ String [] sr = s.split(" "); Student student = new Student(sr[1],Integer.parseInt(sr[2])); Sites.put(sr[0],student); } else break; } } } class Student{ private String name; private int scores; public Student(String name, int scores) { this.name = name; this.scores = scores; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getScores() { return scores; } public void setScores(int scores) { this.scores = scores; } }将这个按学号排序
时间: 2024-02-14 12:13:28 浏览: 19
要按学号排序,可以使用 TreeMap 来代替 HashMap,因为 TreeMap 是有序的键值对集合,可以按键自然顺序或者指定的比较器进行排序。在这里,我们可以指定一个比较器来按学号进行排序,具体实现如下:
```java
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String s = null;
TreeMap<String, Student> sites = new TreeMap<>(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
}); // 使用 TreeMap 替换 HashMap,并指定比较器按学号排序
while (!"end".equals(s)) {
s = input.nextLine();
if (!"end".equals(s)) {
String[] sr = s.split(" ");
Student student = new Student(sr[1], Integer.parseInt(sr[2]));
sites.put(sr[0], student);
} else
break;
}
// 遍历 TreeMap,输出学生信息
for (Map.Entry<String, Student> entry : sites.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue().getName() + " " + entry.getValue().getScores());
}
}
}
class Student {
private String name;
private int scores;
public Student(String name, int scores) {
this.name = name;
this.scores = scores;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScores() {
return scores;
}
public void setScores(int scores) {
this.scores = scores;
}
}
```
在这个程序中,我们使用 TreeMap 来替换 HashMap,并指定一个比较器来按学号进行排序。在遍历 TreeMap 时,会按照学号的顺序输出学生信息。