修改题目143 修改教师类,使得由多个Teacher对象所形成的数组可以排序(编号由低到高排序),并在main函数中使用Arrays.sort(Object[] a)方法排序 定义一个类TeacherManagement,包含教师数组,提供方法add(Teacher[]),使其可以添加教师,提供重载方法search,方法可以在一组给定的教师中,根据姓名或年龄返回等于指定姓名或年龄的教师的字符串信息,信息格式为:“no: , name:, age: **, seminary: **”。如果没有满足条件的教师,则返回“no such teacher”。 输入格式: 教师个数 教师信息 待查找教师的姓名 待查找教师的年龄 输出格式: 排序后的信息 按姓名查找的老师信息 按年龄查找的老师信息 输入样例: 在这里给出一组输入。例如: 4 3 Linda 38 SoftwareEngineering 1 Mindy 27 ComputerScience 4 Cindy 28 SoftwareEngineering 2 Melody 27 ComputerScience Cindy 27 输出样例: 在这里给出相应的输出。例如: no: 1, name: Mindy, age: 27, seminary: ComputerScience no: 2, name: Melody, age: 27, seminary: ComputerScience no: 3, name: Linda, age: 38, seminary: SoftwareEngineering no: 4, name: Cindy, age: 28, seminary: SoftwareEngineering search by name: no: 4, name: Cindy, age: 28, seminary: SoftwareEngineering search by age: no: 1, name: Mindy, age: 27, seminary: ComputerScience no: 2, name: Melody, age: 27, seminary: ComputerScience
时间: 2023-05-22 07:03:50 浏览: 141
可以尝试这样实现:
```java
import java.util.Arrays;
class Teacher {
String name;
int age;
String seminary;
int no;
public Teacher(String name, int age, String seminary, int no) {
this.name = name;
this.age = age;
this.seminary = seminary;
this.no = no;
}
@Override
public String toString() {
return "no: " + no + ", name: " + name + ", age: " + age + ", seminary: " + seminary;
}
}
class TeacherManagement {
Teacher[] teachers;
public TeacherManagement(Teacher[] teachers) {
this.teachers = teachers;
}
public void add(Teacher[] newTeachers) {
int oldLength = teachers.length;
int newLength = oldLength + newTeachers.length;
teachers = Arrays.copyOf(teachers, newLength);
System.arraycopy(newTeachers, 0, teachers, oldLength, newTeachers.length);
}
public String search(String name) {
for (Teacher teacher : teachers) {
if (teacher.name.equals(name)) {
return teacher.toString();
}
}
return "no such teacher";
}
public String search(int age) {
for (Teacher teacher : teachers) {
if (teacher.age == age) {
return teacher.toString();
}
}
return "no such teacher";
}
public void sort() {
Arrays.sort(teachers, (t1, t2) -> t1.no - t2.no);
}
}
public class Main {
public static void main(String[] args) {
java.util.Scanner scanner = new java.util.Scanner(System.in);
int n = scanner.nextInt();
Teacher[] teachers = new Teacher[n];
for (int i = 0; i < n; i++) {
int no = i + 1;
String name = scanner.next();
int age = scanner.nextInt();
String seminary = scanner.next();
teachers[i] = new Teacher(name, age, seminary, no);
}
TeacherManagement manager = new TeacherManagement(teachers);
manager.sort();
for (Teacher teacher : manager.teachers) {
System.out.println(teacher);
}
String searchName = scanner.next();
String result1 = manager.search(searchName);
System.out.println("search by name: " + result1);
int searchAge = scanner.nextInt();
String result2 = manager.search(searchAge);
System.out.println("search by age: " + result2);
}
}
```
PS: 以上回答均为人工智能程序自动生成,若有不恰当之处敬请谅解。
阅读全文