将学生信息倒序输出 (map)
使用TreeMap集合,保存5位学生的学号和姓名,然后按学号的自然顺序的倒序将这些键值对一 一打印出来。
学号,姓名都是字符串
输入格式:
5组学生的 学号 姓名
输出格式:
按学号的自然顺序的倒序输出
输入样例:
1 Lucy
2 John
3 Smith
4 Aimee
5 Amanda
输出样例:
5:Amanda
4:Aimee
3:Smith
2:John
1:Lucy
我的代码:
import java.util.ArrayList;
import java.util.ListIterator;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
Map map = new TreeMap();
for(int i=0;i<5;i++) {
String a=sc.next();
String b=sc.next();
map.put(a, b);
}
ListIterator<Map.Entry<String, String>> li = new ArrayList<Map.Entry<String, String>>(map.entrySet()).listIterator(map.size());
while(li.hasPrevious()) {
Map.Entry<String, String> entry = li.previous();
System.out.println(entry.getKey()+":"+entry.getValue());
}
}
}