我想按照升序排序学生班的3个对象 学生班级中浮点数组的计算平均值。我创建了一个接受两个参数并返回学生平均值的界面,但我不确定如何按计算的平均值对学生班级的3个对象进行排序。
public class Student implements ICalculateAvg
{
private String name;
private String gender;
private String idNumber;
private Subject subject;
//Getters and setters
@Override
public float calculateAverage(float firstGrade, float secondGrade) {
return (firstGrade+secondGrade)/subject.getGrade().length;
}
}
public class Subject
{
private String subjectCode[];
private String name[];
private float grade[];
// Getters and setters
}
打印学生班级的内容会产生以下输出。
Student [name=Mary, gender=Female, idNumber=105, subject=Subject [subjectCode=[SPN3010, FRN1720], name=[Spanish, French], grade=[78.0, 98.0]]]
Student [name=John, gender=Male, idNumber=102, subject=Subject [subjectCode=[SPN3010, FRN1720], name=[Spanish, French], grade=[90.0, 91.0]]]
Student [name=James, gender=Male, idNumber=101, subject=Subject [subjectCode=[SPN3010, FRN1720], name=[Spanish, French], grade=[12.0, 34.0]]]
这是我主要方法中的一些内容。我试图使用比较器和类似的界面来完成所需的结果,但我无法让它工作。
float [] studenGrades1 = {12f, 34f};
float [] studenGrades2 = {90f, 91f};
float [] studenGrades3 = {78f, 98f};
Student student1 = new Student("James Brown", "Male", "101", new Subject(subjectCode, subjectName, studenGrades1));
Student student2 = new Student("John Doe", "Male", "102", new Subject(subjectCode, subjectName, studenGrades2));
Student student3 = new Student("Mary Jame", "Female", "105", new Subject(subjectCode, subjectName, studenGrades3));
float studentFinalGrade1 = student1.calculateAverage(student1.getSubject().getValueAtArrayIndex(0), student1.getSubject().getValueAtArrayIndex(1));
float studentFinalGrade2 = student2.calculateAverage(student2.getSubject().getValueAtArrayIndex(0), student2.getSubject().getValueAtArrayIndex(1));
float studentFinalGrade3 = student3.calculateAverage(student3.getSubject().getValueAtArrayIndex(0), student3.getSubject().getValueAtArrayIndex(1));
答案 0 :(得分:0)
我没有给出完整的代码,只有逻辑:
Collections.sort(studentList, new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
float grade1[] = s1.getSubject().getGrade();
float grade2[] = s2.getSubject().getGrade();
Float avg1=null;//calculate average from grade1
Float avg2=null;//calculate average from grade2
return avg1.compareTo(avg2);
}
});