编写学生类,包含学号no、姓名name、成绩score,提供必要的构造函数、toString函数和equals/hashcode函数,其中,toString函数的格式为“no:xxx name:xxx score:xxx”,no参与equals和hashcode的计算 在main函数中构造一个Map容器存放学生对象 从命令行输入多个学生对象,存入Map中,其中key为学号,value为学生对象。 从命令行中读入在学生集合上的操作,具体操作包含: add 添加一个学生(包含学号和学生姓名) delete 删除一个学生(包含学号) set 修改一个学生信息(只修改某学号学生的成绩) 完成操作后按学生的学号从小到大的顺序输出所有学生的信息
输出时按照学生的学号顺序输出
输入格式:
学生个数
学生对象数据
操作数
操作内容
输出格式:
按照学号顺序输出集合中的学生
输入样例:
在这里给出一组输入。例如:
4
1 wong 90
2 liu 80
3 chen 70
4 fang 60
3
add 5 duan 80
delete 3
set 4 70
输出样例:
在这里给出相应的输出。例如:
no:1 name:wong score:90
no:2 name:liu score:80
no:4 name:fang score:70
no:5 name:duan score:80
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
栈限制
8192 KB
import java.util.*;
class Student{
private Integer no;
private String name;
private Integer score;
public Student(Integer no,String name,Integer score){
this.no=no;
this.name=name;
this.score=score;
}
public void setScore(Integer score){
this.score=score;
}
public String toString(){
return String.format("no:%d name:%s score:%d",no,name,score);
}
public boolean equals(Object o){
if(this==o) return true;
if(o==null||getClass()!= o.getClass())return false;
Student student=(Student) o;
return Objects.equals(no, student.no);
}
public int hashCode(){
return Objects.hash(no);
}
}
public class Main{
public static void main(String[] args){
Scanner scanner=new Scanner(System.in);
Map<Integer,Student> studentMap=new HashMap<>();
int n=Integer.parseInt(scanner.nextLine().trim());
for(int i=0;i<n;i++){
String[] parts=scanner.nextLine().trim().split("\\s+");
Integer no=Integer.parseInt(parts[0]);
String name=parts[1];
Integer score=Integer.parseInt(parts[2]);
studentMap.put(no,new Student(no,name,score));
}
int m=Integer.parseInt(scanner.nextLine().trim());
for(int i=0;i<m;i++){
String[] parts=scanner.nextLine().trim().split("\\s+");
String operation=parts[0];
switch (operation){
case "add":
Integer addNo=Integer.parseInt(parts[1]);
String name =parts[2];
Integer addScore=Integer.parseInt(parts[3]);
studentMap.put(addNo,new Student(addNo,name,addScore));
break;
case "delete":
Integer delNo=Integer.parseInt(parts [1]);
studentMap.remove(delNo);
break;
case"set":
Integer setNo =Integer.parseInt(parts[1]);
Integer newScore=Integer.parseInt(parts[2]);
Student student=studentMap.get(setNo);
if(student !=null){
student.setScore(newScore);
}
break;
}
}
List<Integer>sortedkeys=new ArrayList<>(studentMap.keySet());
Collections.sort(sortedkeys);
for(Integer key: sortedkeys){
System.out.println(studentMap.get(key));
}
}
}