用java编写定义包含学号、姓名和成绩信息的学生类Student。在测试类中定义存放n个学生对象存放到某个集合对象中(具体集合自行确定),然后按成绩进行降序排列,并将排序结果(类Student对象)保存到文件stud.dat中,再读出文件stud.dat中所有的学生信息并显示。
时间: 2024-02-29 18:52:28 浏览: 60
以下是学生类Student的定义:
```java
public class Student implements Comparable<Student> {
private int sid;
private String name;
private double score;
public Student(int sid, String name, double score) {
this.sid = sid;
this.name = name;
this.score = score;
}
public int getSid() {
return sid;
}
public String getName() {
return name;
}
public double getScore() {
return score;
}
public void setSid(int sid) {
this.sid = sid;
}
public void setName(String name) {
this.name = name;
}
public void setScore(double score) {
this.score = score;
}
public void display() {
System.out.println("学号:" + sid + ",姓名:" + name + ",成绩:" + score);
}
@Override
public int compareTo(Student o) {
return Double.compare(o.score, score);
}
}
```
在这里,我们实现了Comparable接口,重写了compareTo方法,以实现按成绩降序排列。
以下是测试类的实现:
```java
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
List<Student> students = new ArrayList<Student>();
Scanner scanner = new Scanner(System.in);
System.out.print("请输入学生人数:");
int n = scanner.nextInt();
for (int i = 0; i < n; i++) {
System.out.print("请输入第" + (i + 1) + "个学生的学号、姓名、成绩:");
int sid = scanner.nextInt();
String name = scanner.next();
double score = scanner.nextDouble();
Student student = new Student(sid, name, score);
students.add(student);
}
Collections.sort(students);
try {
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("stud.dat"));
for (Student student : students) {
out.writeObject(student);
}
out.close();
ObjectInputStream in = new ObjectInputStream(new FileInputStream("stud.dat"));
List<Student> sortedStudents = new ArrayList<Student>();
while (true) {
try {
Student student = (Student) in.readObject();
sortedStudents.add(student);
} catch (EOFException e) {
break;
}
}
in.close();
System.out.println("按成绩降序排列后的学生信息如下:");
for (Student student : sortedStudents) {
student.display();
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
```
在测试类中,我们首先用一个ArrayList容器存放n个学生对象,然后按成绩进行降序排列,最后将结果保存到文件stud.dat中。在读取文件时,我们使用ObjectInputStream类,while循环读取所有的学生信息,并将其存放到一个新的ArrayList容器sortedStudents中。最后,我们再输出这个容器中的所有学生信息。
阅读全文