Treemap

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();
    }

}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值