8-1 学生成绩管理 (20 分)
设计学生类Student,属性:学号(整型);姓名(字符串),选修课程(名称)及课程成绩(整型)。编写一个控制台程序,能够实现Student信息的保存、读取。
具体要求:
(1)提供Student信息的保存功能:通过控制台输入若干个学生的学号、姓名以及每个学生所修课程的课程名和成绩,将其信息保存到data.dat中;
(2)数据读取显示:能够从data.dat文件中读取学生及其课程成绩并显示于控制台。@
代码
代码仅供参考
import java.io.*;
import java.util.*;
class Student implements Serializable {
public int id;
public String name;
public String kn;
public int score;
public Student(int id, String name, String kn, int score) {
super();
this.id = id;
this.name = name;
this.kn = kn;
this.score = score;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", kn=" + kn + ", score=" + score + "]";
}
}
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
LinkedList<Student> list = new LinkedList<>();
System.out.print("请输入学生人数:");
int num = sc.nextInt();
System.out.println("请依次输入学生的学号、姓名以及每个学生所修课程的课程名和成绩:");
for (int i = 0; i < num; i++) {
list.add(new Student(sc.nextInt(), sc.next(), sc.next(), sc.nextInt()));
}
ObjectInputStream ois = null;
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(new FileOutputStream("data.dat"));
oos.writeObject(list);
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
oos.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
try {
ois = new ObjectInputStream(new FileInputStream("data.dat"));
System.out.println(ois.readObject());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}