7-4 学生Map (20 分)
编写学生类,包含学号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
import java.util.*;
import java.util.Map.Entry;
class student{
String name;
String no,score;
public student(String name, String no, String score) {
super();
this.name = name;
this.no = no;
this.score = score;
}
public String getScore() {
return score;
}
public void setScore(String score) {
this.score = score;
}
@Override
public String toString() {
return "no:" + no + " name:" + name + " score:" + score ;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((no == null) ? 0 : no.hashCode());
result = prime * result + ((score == null) ? 0 : score.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
/*if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
student other = (student) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (no == null) {
if (other.no != null)
return false;
} else if (!no.equals(other.no))
return false;
if (score == null) {
if (other.score != null)
return false;
} else if (!score.equals(other.score))
return false;*/
student other = (student) obj;
if (no == null) {
if (other.no != null)
return false;
} else if (!no.equals(other.no))
return false;
return true;
}
}
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
Map<String,student> mp=new TreeMap();
for(int i=0;i<n;i++) {
String no=sc.next();
String na=sc.next();
String s=sc.next();
student st =new student(na,no,s);
mp.put(no, st) ;
}
n=sc.nextInt();
for(int i=0;i<n;i++) {
String a=sc.next();
if(a.charAt(0)=='a') {
String no=sc.next();
String na=sc.next();
String s=sc.next();
student st =new student(na,no,s);
mp.put(no, st);
}else if(a.charAt(0)=='d'){
String no=sc.next();
mp.remove(no);
}else {
String no=sc.next();
String y=sc.next();
mp.get(no).setScore(y);
}
}
Iterator it=mp.entrySet().iterator();
while(it.hasNext()) {
Entry ex=(Entry)it.next();
if(it.hasNext()) {
System.out.println(ex.getValue().toString());
}
else
System.out.print(ex.getValue().toString());
}
}
}