用java先从键盘录入5个学生的数据,保存到容器对象ar中,然后按照名字升序排序之后输出。
时间: 2023-05-21 18:01:24 浏览: 128
好的,以下是Java代码实现:
```java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<Student> ar = new ArrayList<>();
for (int i = 0; i < 5; i++) {
System.out.println("请输入第" + (i + 1) + "个学生的姓名和成绩:");
String name = scanner.next();
int score = scanner.nextInt();
ar.add(new Student(name, score));
}
Collections.sort(ar, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o1.getName().compareTo(o2.getName());
}
});
System.out.println("按照名字升序排序后的结果为:");
for (Student student : ar) {
System.out.println(student.getName() + " " + student.getScore());
}
}
}
class Student {
private String name;
private int score;
public Student(String name, int score) {
this.name = name;
this.score = score;
}
public String getName() {
return name;
}
public int getScore() {
return score;
}
}
```
希望能够帮到您!
阅读全文