设计思路:
比较器首先Comparable<T>,并使用Array.sort()进行排序,最后使用Array.toString()进行输出显示。
代码实现:
首先进行学生类的创建,学生类进行接口Comparable<T>的实现。
public class Student implements Comparable<Student>{ private String name; private double score; public Student() { } public Student(String name, double score) { this.name = name; this.score = score; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getScore() { return score; } public void setScore(double score) { this.score = score; } @Override public String toString() { // 变量变字符串 return "|" + "姓名:" + name + ", 成绩:" + score + "|"; } @Override public int compareTo(Student student) { // 重写方法,比较大小,小于返回负整数,等于返回0,大于返回正整数 return (int)(this.score - student.score); } }
然后定义一个学生信息设置类进行对学生的姓名和成绩进行设置:
import java.util.Scanner; public class SetStudent{ public Student[] setStudentsArray(){ // 设置个数并返回学生类数组 Scanner sc = new Scanner(System.in); System.out.print("请输入添加的个数:"); int count = sc.nextInt(); Student[] students = new Student[count]; for (int i = 0; i < count; i++) { System.out.println("第【"+(i+1)+"】个:"); students[i] = new SetStudent().setStudent(new Student()); // 设置数组元素 } return students; // 返回学生类数组 } private Student setStudent(Student student){ // 设置学生姓名和成绩信息 Scanner sc = new Scanner(System.in); System.out.print("姓名:"); student.setName(sc.next()); System.out.print("成绩:"); student.setScore(sc.nextDouble()); return student; } }
利用工厂类进行对象数组的获取:
public class Factory{ public static Student[] getInstance(){ return new SetStudent().setStudentsArray(); } }
客户端调用:
import java.util.Arrays; public class MAIN { public static void main(String[] args) { Student[] st = Factory.getInstance(); Arrays.sort(st); System.out.println(Arrays.toString(st)); } }
以上就是进行学生信息输入并排序后打印的简单代码实现。