7-3 学生列表 (20 分)
编写学生类,包含学号no、姓名name、成绩score,提供必要的构造函数、toString函数和equals/hashcode函数,其中,toString函数的格式为“no:xxx name:xxx score:xxx”,no参与equals和hashcode的计算 在main函数中构造一个学生列表对象(List),用于存放多个学生对象 从命令行输入多个学生对象,存入列表中 从命令行中读入在列表对象上的操作,具体操作包含: 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;
}
@Override
public String toString() {
return
"no:" + no +
" name:" + name +
" score:" + score;
}
@Override
public 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;
}
@Override
public 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);
List<Student> ls = new LinkedList<>();
int n = sc.nextInt();
for(int i = 1; i <= n; i++){
int no = sc.nextInt();
String name = sc.next();
int score = sc.nextInt();
ls.add(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();
ls.add(new Student(no, name, score));
}
else if(op.equals("delete")){
int id = sc.nextInt();
Student s = new Student(id);
ls.remove(s);
}
else{
int id = sc.nextInt();
id = ls.indexOf(new Student(id));
int score = sc.nextInt();
ls.get(id).setScore(score);
}
}
for (Student it : ls){
System.out.println(it.toString());
}
}
}