7-6 学生列表2 (25分)
编写学生类,包含学号no、姓名name、成绩score,提供必要的构造函数、toString函数和equals/hashcode函数,其中,toString函数的格式为“no:xxx name:xxx score:xxx”,no参与equals和hashcode的计算 在main函数中构造一个容器存放学生对象 从命令行输入多个学生对象,存入列表中 从命令行中读入在列表对象上的操作,具体操作包含: 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
package another;
import java.util.*;
import java.io.*;
public class Main{
public static void main(String[] args){
Scanner scan=new Scanner(System.in);
List<Student> stuList=new ArrayList<Student>();
int n=scan.nextInt();
scan.nextLine();
for(int i=0;i<n;i++)
{
String line=scan.nextLine();
String[] words=line.split(" ");
int no=Integer.parseInt(words[0]);
int score=Integer.parseInt(words[2]);
stuList.add(new Student(no,words[1],score));
}
int nn=scan.nextInt();
scan.nextLine();
for(int i=0;i<nn;i++)
{
String line=scan.nextLine();
String[] words=line.split(" ");
if("add".equals(words[0]))
{
int no=Integer.parseInt(words[1]);
int score=Integer.parseInt(words[3]);
stuList.add(new Student(no,words[2],score));
}
else if("delete".equals(words[0]))
{
int no=Integer.parseInt(words[1]);
stuList.remove(stuList.indexOf(new Student(no,null,0)));
}
else
{
int no=Integer.parseInt(words[1]);
int score=Integer.parseInt(words[2]);
stuList.get(stuList.indexOf(new Student(no,null,0))).setScore(score);
}
}
Collections.sort(stuList);
for(int i=0;i<stuList.size();i++)
{
System.out.println(stuList.get(i));
}
scan.close();
}
}
class Student implements Comparable{
private String name;
private int no;
private int score;
public Student(int no,String name,int score) {
this.name=name;
this.no=no;
this.score=score;
}
@Override
public String toString() {
return "no:"+no+" name:"+name+" score:"+score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + no;
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 (no != other.no)
return false;
return true;
}
@Override
public int compareTo(Object o) {
Student s=(Student)o;
if(no<s.no)
return -1;
else if(no>s.no)
return 1;
else
return 0;
}
}