本程序实现了学生信息的增删改查等基本功能。其中为了更好的保存信息,本程序以文件的形式来保存信息。
首先,编写了一个Student类来存放学生信息,生成get、set方法以及tostring()方法;
import java.text.DecimalFormat;
public class Student {
//学生信息
private final String name;
private final String num;
private double math;
private double English;
private double web;
private double sum;
private double average;
private final DecimalFormat format; //数字格式化类
public Student(String name, String num, double math, double english, double web) {
this.name = name;
this.num = num;
this.math = math;
this.English = english;
this.web = web;
this.sum = (math+english+web);
format = new DecimalFormat("####.###"); //定义了数字格式,保留三位小数(多余位数直接舍去)
this.average = Double.parseDouble(format.format(this.sum/3));
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", num='" + num + '\'' +
", math=" + math +
", English=" + English +
", web=" + web +
", sum=" + sum +
", average=" + average +
'}';
}`
//get方法
public String getName() {
return name;
}
public String getNum() {
return num;
}
public double getMath() {
return math;
}
public double getEnglish() {
return English;
}
public double getWeb() {
return web;
}
public double getSum() {
return sum;
}
public double getAverage() {
return average;
}
//set方法
public void setMath(double math) {
this.math = math;
}
public void setEnglish(double english) {
English = english;
}
public void setWeb(double web) {
this.web = web;
}
public void setSum(double sum) {
this.sum = sum;
}
public void setAverage(double average) {
this.average = Double.parseDouble(format.format(average));
}
}
接着为学生信息处理编写一个类,其中利用了设计模式中的单例模式,并且采取LinkedList结构来存放新建的学生信息,方便应对未知的学生数量;
对于文件的读取,在程序运行时读入文件信息,在程序关闭时将链表中的信息存入文件中,这样可以避免重复对文件进行操作;避免了I/O抖动的情况;
package com.smj;
import java.io.*;
import java.util.LinkedList;
public class InformationIO {
private static LinkedList<Student> message = null; //存放学生信息
public InformationIO() {
if (message == null) {
message = new LinkedList<>();
try {
//文件原内容读入
File file = new File("message.txt");
if (file.exists()) {
//文件存在时读入数据
BufferedReader buff = new BufferedReader(new FileReader("message.txt"));//打开文件
String row;
while ((row = buff.readLine()) != null) {
String[] str = row.split(";");
message.add(new Student(str[0], str[1], Double.parseDouble(str[2]), Double.parseDouble(str[3]), Double.parseDouble(str[4])));
}
buff.close(); //缓存流关闭
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
//添加学生信息
public static boolean addMessage(String name, String num, double math, double english, double web) {
for (Student stud : message) {
//防止学号重复
if (stud.getNum().equalsIgnoreCase(num)) {
return false;
}
}
message.add(new Student(name, num, math, english, web));
return true;
}
//查看所有学生成绩
public static