2024秋面向对象程序设计-实验二(接口与异常)

import java.lang.reflect.*;

class PerComparatorAES implements Comparator <Person>{

@Override

public int compare(Person o1, Person o2) {

if(o1.getName().equals(o2.getName())){

return o1.getId()-o2.getId();

}

else

return o1.getName().compareTo(o2.getName());

}

}

class TeaComparator implements Comparator <Person> {

@Override

public int compare(Person o1, Person o2) {

if (o1 instanceof Teacher && o2 instanceof Teacher) {

Teacher t1 = (Teacher) o1;

Teacher t2 = (Teacher) o2;

return t1.salary > t2.salary ? -1 : 1;}

else return 0;

}

}

public class Main{

public static void main(String[] args) {

String[] types = {"Student","Teacher"};

Scanner sc = new Scanner(System.in);

Random rand = new Random(sc.nextInt());

int n=sc.nextInt();

Person[] p = new Person[n];

int cnt=0;

for(int i=0;i<n;i++){

int x=rand.nextInt(2);

if(x==0){

System.out.println("Student");

Student student = new Student(sc.next(), sc.next(), sc.nextInt(), sc.next());

p[i]=student;

}

else{

System.out.println("Teacher");

Teacher teacher=new Teacher(sc.next(),sc.next(),sc.next(), sc.nextDouble());

p[i]=teacher;

cnt++;

}}

System.out.println("afterSortDES:");

Arrays.sort(p,new PerComparatorDES());

for (int j = 0; j < n; j++) {

System.out.println(p[j].toString());

}

System.out.println("afterSortAES:");

Arrays.sort(p,new PerComparatorAES());

for (int j = 0; j < n; j++) {

System.out.println(p[j].toString());

}

System.out.println("afterSortTeacher:");

Person f[]=new Person[cnt];

int t=0;

for(int i=0;i<n;i++){

if(p[i]instanceof Teacher){

Teacher teacher=(Teacher) p[i];

f[t]=teacher;

t++;

}

}

Arrays.sort(f,new TeaComparator());

for (int j = 0; j < cnt; j++) {

System.out.println(f[j].toString());

}

Class interfaces1[] = PerComparatorDES.class.getInterfaces();

Class interfaces2[] = PerComparatorAES.class.getInterfaces();

Class interfaces3[] = TeaComparator.class.getInterfaces();

for(Class inf:interfaces1) {

System.out.println(inf);

}

for(Class inf:interfaces2) {

System.out.println(inf);

}

for(Class inf:interfaces3) {

System.out.println(inf);

}}

}

 

上一篇:C语言_动态内存管理


下一篇:ros中launch文件学习(1)-实际案例