用java语言实现如下题目:定义一个学生类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[] studentArray = new Student[num]; for(int i=0;i<num;i++) { String name=in.next(); int year=in.nextInt(); int month=in.nextInt(); int day=in.nextInt(); String studentId=in.next(); String school=in.next(); studentArray[i]=new Student(name,year,month,day,studentId,school); } Arrays.sort(studentArray); for(Student s:studentArray) System.out.println(s); } } class Student implements Comparable { //给出Student的定义 }
时间: 2023-11-22 09:52:06 浏览: 136
代码如下:
```
import java.util.Arrays;
import java.util.Date;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
int num=in.nextInt();
Student[] studentArray = new Student[num];
for(int i=0;i<num;i++) {
String name=in.next();
int year=in.nextInt();
int month=in.nextInt();
int day=in.nextInt();
String studentId=in.next();
String school=in.next();
studentArray[i]=new Student(name,year,month,day,studentId,school);
}
Arrays.sort(studentArray);
for(Student s:studentArray)
System.out.println(s);
}
}
class Student implements Comparable<Student> {
private String name;
private Date birthday;
private String studentId;
private String school;
public Student(String name, int year, int month, int day, String studentId, String school) {
this.name = name;
this.birthday = new Date(year - 1900, month - 1, day);
this.studentId = studentId;
this.school = school;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", birthday=" + birthday +
", studentId='" + studentId + '\'' +
", school='" + school + '\'' +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Student)) return false;
Student student = (Student) o;
return studentId.equals(student.studentId);
}
@Override
public int hashCode() {
return studentId.hashCode();
}
@Override
public int compareTo(Student o) {
return this.studentId.compareTo(o.studentId);
}
}
```
注:上述代码中,我们使用了 `java.util.Date` 类来表示学生的生日,并在 `Student` 构造函数中将输入的年月日转换为 `Date` 类型。同时,我们重写了 `equals` 和 `hashCode` 方法,以确保在使用 `HashSet` 或 `HashMap` 等容器时,能够正确判断学生对象是否相等。
阅读全文