sdut-Colleciton-5 学生信息的添加与查询(HashMap)
设计一个学生信息添加和查询的系统,从键盘读入学生的数据,然后通过屏幕进行显示。
输入格式:
第一行有1个整数N,表示学生数量;
接下来有N行学生数据,分别表示学生的id(编号)、name(姓名)、birthday(生日)、score(成绩)属性的值,关键字(id)相同的记录代表同一个学生(如果id相同,后来读入的学生信息会覆盖已有的学生信息)
输出格式:
按照id从小到大的顺序,输出所有学生的属性名称及属性值,其中score(成绩)保留1位有效数字,具体输出格式见输出样例。
提示:可以利用Student类的toString()方法来实现类对象属性的展示。
样例">输入样例:
5
0001 Mike 1990-05-20 98.5
0002 John 1992-05-20 67
0003 Hill 1994-05-20 36.5
0004 Christ 1996-05-20 86.5
0001 Jack 1998-05-20 96
输出样例:
Student [id=0001, name=Jack, birthday=1998年05月20日, score=96.0]
Student [id=0002, name=John, birthday=1992年05月20日, score=67.0]
Student [id=0003, name=Hill, birthday=1994年05月20日, score=36.5]
Student [id=0004, name=Christ, birthday=1996年05月20日, score=86.5]
代码如下:使用TreeMap比较方便
import java.text.ParseException;
import java.util.*;
class Student {
String id;
String name;
String birthday;
double score;
public Student(String id, String name, String birthday, double score) {
this.id = id;
this.name = name;
this.birthday = birthday;
this.score = score;
}
@Override
public String toString(){
String[] s = birthday.split("-");
return "Student [id="+id+", name="+name+", birthday="+s[0]+"年"+s[1]+"月"+s[2]+"日"+", score="+score+"]";
}
}
public class Main {
public static void main(String[] args) throws ParseException {
Scanner sc = new Scanner(System.in);
//TreeMap可以默认用key排序(升序)
Map<String,Student> map = new TreeMap();
int n = sc.nextInt();
for(int i = 0;i<n;i++){
String id = sc.next();
String name = sc.next();
String birthday = sc.next();
double score = sc.nextDouble();
Student s = new Student(id,name,birthday,score);
//将key设置为id,就可以实现对id(String类型)的升序排列
map.put(id,s);
}
//entrySet是 java中 键-值 对的集合,Set里面的类型是Map.Entry
//可以通过map.entrySet()得到,entrySet实现了Set接口,里面存放的是键值对。一个K对应一个V。
//有方法getKey和方法getValue来获得键或者值,直接打印将输出key=value
for (Map.Entry<String, Student> e : map.entrySet()){
System.out.println(e.getValue());//只得到Value值
}
sc.close();
}
}