PTA 7-4 学生Map (20 分) JAVA

编写学生类,包含学号no、姓名name、成绩score,提供必要的构造函数、toString函数和equals/hashcode函数,其中,toString函数的格式为“no:xxx name:xxx score:xxx”,no参与equals和hashcode的计算 在main函数中构造一个Map容器存放学生对象 从命令行输入多个学生对象,存入Map中,其中key为学号,value为学生对象。 从命令行中读入在学生集合上的操作,具体操作包含: add 添加一个学生(包含学号和学生姓名) delete 删除一个学生(包含学号) set 修改一个学生信息(只修改某学号学生的成绩) 完成操作后按学生的学号从小到大的顺序输出所有学生的信息 输出时按照学生的学号顺序输出

import java.util.*;class Student{int no;String name;int score;public Student(int no, String name, int score) {this.no = no;this.name = name;this.score = score;}public Student(int no) {this.no = no;}@Overridepublic String toString() {return"no:" + no +" name:" + name +" score:" + score;}@Overridepublic boolean equals(Object o) {if (this == o) return true;if (o == null || getClass() != o.getClass()) return false;Student student = (Student) o;return no == student.no;}@Overridepublic int hashCode() {return Objects.hash(no);}public void setScore(int score) {this.score = score;}
}
public class Main {public static void main(String[] args) {Scanner sc = new Scanner(System.in);TreeMap<Integer, Student> ms = new TreeMap<>();int n = sc.nextInt();for(int i = 1; i <= n; i++){int no = sc.nextInt();String name = sc.next();int score = sc.nextInt();ms.put(no, new Student(no, name, score));}n = sc.nextInt();for(int i = 1; i <= n; i++){String op = sc.next();if(op.equals("add")){int no = sc.nextInt();String name = sc.next();int score = sc.nextInt();ms.put(no, new Student(no, name, score));}else if(op.equals("delete")){int id = sc.nextInt();ms.remove(id);}else{int id = sc.nextInt();int score = sc.nextInt();ms.get(id).setScore(score);}}// 在Integer内已经定义了cmp,并且这个map的键又是学号,默认就是已经对序号从小到大排序了for (Integer it : ms.keySet()){System.out.println(ms.get(it).toString());}}
}


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部