定义一个学生类Student,成员变量包括:姓名,生日,学号,学校;重写方法toString,equals,hashCode;实现接口Comparable,按照学号大小进行比较;定义构造方法。 代码形式如下: public class Main{ public static void main(String[] args) { Scanner in=new Scanner(System.in); int num=in.nextInt(); Student[
时间: 2023-11-22 14:52:28 浏览: 98
设计一个学生类Student(学生学号、姓名、数学、英语、计算机成绩;)
5星 · 资源好评率100%
public class Student implements Comparable<Student>{
private String name;
private Date birthday;
private String id;
private String school;
public Student(String name, Date birthday, String id, String school) {
this.name = name;
this.birthday = birthday;
this.id = id;
this.school = school;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", birthday=" + birthday +
", id='" + id + '\'' +
", school='" + school + '\'' +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Student)) return false;
Student student = (Student) o;
return getId().equals(student.getId());
}
@Override
public int hashCode() {
return Objects.hash(getId());
}
@Override
public int compareTo(Student o) {
return this.getId().compareTo(o.getId());
}
public String getName() {
return name;
}
public Date getBirthday() {
return birthday;
}
public String getId() {
return id;
}
public String getSchool() {
return school;
}
}
//在Main类中使用
public class Main{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int num = in.nextInt();
Student[] students = new Student[num];
for (int i = 0; i < num; i++) {
String name = in.next();
Date birthday = new Date(in.next());
String id = in.next();
String school = in.next();
students[i] = new Student(name, birthday, id, school);
}
Arrays.sort(students);
for (Student student : students) {
System.out.println(student.toString());
}
}
}
阅读全文