定义一个学生类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的定义
}
输入格式:
第一行输入学生人数。其他各行每行输入一个学生的姓名,出生年月日,学号,学号,用空格分隔。
输出格式:
按照学号从小到大排序的学生信息,每个学生信息一行。
输入样例:
例如:
3
李翔 2002 10 9 202019001 北京化工大学
张凯 2002 11 23 202019015 北京化工大学
汪海 2002 7 5 202019012 北京化工大学
输出样例:
例如:
Student[name=李翔, birthday=2002-10-09, studentId=202019001, school=北京化工大学]
Student[name=汪海, birthday=2002-07-05, studentId=202019012, school=北京化工大学]
Student[name=张凯, birthday=2002-11-23, studentId=202019015, school=北京化工大学]
代码实现区:
import java.util.Arrays;
import java.util.Comparator;
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, Comparator.comparingInt(o -> Integer.parseInt(o.studentId)));
for(Student s:studentArray)
System.out.println(s);
}
}
class Student implements Comparable
{
String name,school,studentId;
int year,month,day;
public Student(String name, int year, int month, int day, String studentId, String school)
{
this.name=name;
this.studentId=studentId;
this.day=day;
this.year=year;
this.month=month;
this.school=school;
}
public String toString() {
return "Student[name="+name+", birthday="+year+"-"+String.format("%02d",month)+"-"+String.format("%02d",day)+", studentId="+studentId+", school="+school+"]";
}
public boolean equals(Object obj) {
return super.equals(obj);
}
public int hashCode() {
return super.hashCode();
}
public int compareTo(Object o) {
return 0;
}
}