编写一个程序,综合运用集合、IO流等相关操作,编程实现以下要求:
1)?? 定义一个父类,并定义多个不同子类,子类分别以不同方式重写父类的方法;
2)?? 定义多个类型的对象,编写方法实现多态效果;
3)?? 将多个对象存放在一个适当的集合中,集合中要使用泛型;
4)?? 使用合适的方法对集合中的数据按一定的方式排序;
5)?? 使用迭代器遍历集合并输出集合的元素,将排序后输出的结果写入out.txt文件中,IO操作需要有异常处理;
例如:定义学生父类和不同阶段学生子类(本科生、研究生等),包含学生信息(学号、姓名、成绩或年龄等),子类要实现父类的方法,要有不同的表现。将对象存入集合中,可以按学号或成绩排序。?
import java.util.Comparator;
import java.util.TreeSet;
import java.util.Iterator;
import java.io.*;
public class TextZhonghe {
public static void main(String[] args) throws Exception {
Student s1 = new Student("张一", 2020145, 18, 98);
Undergraduate s2 = new Undergraduate("李一", 2020111, 21, 100, "法学");
Graduate s3 = new Graduate("张二", 2020001, 19, 96, "朱老师");
System.out.println(s1.show());
System.out.println(s2.show());
System.out.println(s3.show());
System.out.println("---------");
TreeSet<Student> ts = new TreeSet<>(new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
int num = o1.getName().compareTo(o2.getName());
return num == 0 ? num : o1.getScore() - o2.getScore();
}
}
);
ts.add(s1);
ts.add(s2);
ts.add(s3);
ts.add(new Student("张三", 2020231, 18, 68));
ts.add(new Student("李二", 2020123, 19, 45));
Iterator it = ts.iterator();
while (it.hasNext()) {
Object obj = it.next();
System.out.println(obj);
}
BufferedWriter bw = new BufferedWriter(new FileWriter("F:/zh.txt"));
for(Student s:ts){
bw.write(s.getName()+" "+s.getScore());
bw.newLine();
}
bw.close();
}
}
class Student{ //父类学生类
private String name;
private int age;
private int sno; //学号
private int score;
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
public int getAge(){
return age;
}
public void setAge(int age){
this.age=age;
}
public void setSno(int sno){
this.sno=sno;
}
public int getSno(){
return sno;
}
public int getScore(){
return score;
}
public void setScore(){
this.score=score;
}
public Student(String name,int sno,int age,int score){
this.age=age;
this.sno=sno;
this.name=name;
this.score=score;
}
public String show(){
return name+": 学号:"+sno+", 年龄:"+age+",成绩:"+score;
}
public String toString(){
return sno+":"+name+" "+score;
}
}
class Undergraduate extends Student{
private String major;
public String getMajor(){
return major;
}
public void setMajor(String major){
this.major=major;
}
public Undergraduate(String name,int sno,int age,int score,String major){
super(name,sno,age,score);
this.setMajor(major);
}
public String show(){
return super.show()+",专业:"+this.getMajor();
}
}
class Graduate extends Student{
private String teacher;
public String getTeacher(){
return teacher;
}
public void setTeacher(String teacher){
this.teacher=teacher;
}
public Graduate(String name,int sno,int age,int score,String teacher){
super(name,sno,age, score);
this.setTeacher(teacher);
}
public String show(){
return super.show()+",导师:"+this.getTeacher();
}
}
三:实验结果: