定义一个Student类,包括姓名和成绩两个属性,在main()函数中定义一个长度为5的Student类数组,从控制台循环输入学生姓名和成绩,然后输出在控制台上,将学生的成绩按照降序排序并输出:
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
public class Student {
//姓名
private String name;
//成绩
private float score;
public Student(String name, float score) {
this.name = name;
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getScore() {
return score;
}
public void setScore(float score) {
this.score = score;
}
public static void main(String[] args) {
int num = 5;
List<Student> studentList = new ArrayList<>();
for(int i=0; i<num ;i++){
System.out.println("请输入第"+ (i + 1) + "同学的姓名");
String name = new Scanner(System.in).nextLine();
System.out.println("请输入第"+ (i + 1) + "同学的成绩");
float score = new Scanner(System.in).nextFloat();
studentList.add(new Student(name,score));
}
System.out.println("排序前学生信息:");
for(int i=0; i<num; i++){
Student student = studentList.get(i);
System.out.println(student.getName() + " " + student.getScore());
}
studentList.sort(new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return Float.compare(o2.getScore(), o1.getScore());
}
});
System.out.println("排序后学生信息:");
for(int i=0; i<num; i++){
Student student = studentList.get(i);
System.out.println(student.getName() + " " + student.getScore());
}
}
}