大commit - 能跑起来了

# 更新概览
ManagerTool:
- 删除学生时新增判空及保存
StudentManager:
- 添加学生时去重,以id和姓名区分
- 信息生成方法生成格式调整(省去末尾换行符)
- 信息生成方法返回值类型修改为String而不是直接生成String
- 拆分部分信息生成方法
- 新增部分对外方法
Worker:
- 完成几乎所有命令的方法调用
- 添加名字可多次添加,以“:wq"完成
main
lensfrex 3 years ago
parent e2e7646666
commit 3cbe689b9e
Signed by: lensfrex
GPG Key ID: 947ADABD8533C476
  1. 2
      readme.md
  2. 80
      src/main/java/me/lensfrex/manager/Main.java
  3. 2
      src/main/java/me/lensfrex/manager/data/Student.java
  4. 25
      src/main/java/me/lensfrex/manager/data/manager/ManagerTool.java
  5. 146
      src/main/java/me/lensfrex/manager/data/manager/StudentManager.java
  6. 12
      src/main/java/me/lensfrex/manager/utils/Console.java
  7. 33
      src/main/java/me/lensfrex/manager/utils/DataLoader.java
  8. 150
      src/main/java/me/lensfrex/manager/utils/Worker.java
  9. 19
      src/main/resources/me.lensfrex.manager/helpMessage.txt
  10. 5
      src/main/resources/me.lensfrex.manager/studentInformationExample.txt
  11. 18
      src/main/resources/me.lensfrex.manager/welcomeMessage.txt

@ -6,6 +6,6 @@
就一小作业而已
写的很粗糙,没有仔细考虑,还望谅解 ( ̄﹏ ̄;)
写的很粗糙,没有仔细考虑,性能,扩展性什么的都没有考虑,还望谅解 ( ̄﹏ ̄;)

@ -1,34 +1,27 @@
package me.lensfrex.manager;
import me.lensfrex.manager.utils.IOUtil;
import me.lensfrex.manager.utils.Console;
import me.lensfrex.manager.utils.Worker;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
public class Main {
private static final String welcomeMessage = IOUtil.inputStreamToString(Main.class.getResourceAsStream("/me.lensfrex.manager/welcomeMessage.txt"), StandardCharsets.UTF_8);
public static void main(String[] args) {
System.out.println(welcomeMessage);
new Main().run();
}
private void run() {
while (true) {
if (parseCommand(getUserCommand()) == -1) {
break;
}
}
}
Worker worker = new Worker();
private String getUserCommand() {
BufferedReader command = new BufferedReader(new InputStreamReader(System.in));
try {
return command.readLine();
} catch (Exception e) {
e.printStackTrace();
return "null";
Console consoleTool = new Console();
private void run() {
while (parseCommand(consoleTool.getUserInput()) != -1) {
System.out.println(
"****************************************************************\n" +
" Please enter your choice:"
);
}
}
@ -38,21 +31,64 @@ public class Main {
case "0":
return -1;
case "1":
System.out.println(Worker.studentInformationExample);
for (;;) {
String userInput = consoleTool.getUserInput();
if (userInput.equals(":wq")) {
break;
}
worker.addStudent(userInput);
}
break;
case "2":
String userInput = consoleTool.getUserInput();
//System.out.println("Are you sure to delete" + userInput + "? (yes/no)");
try {
long id = Long.parseLong(userInput);
worker.removeStudent(id);
} catch (NumberFormatException e) {
worker.removeStudent(userInput);
}
break;
case "3":
worker.printAllSubjectInfo();
break;
case "4":
worker.printAllStudentScoreInfo();
break;
case "5":
worker.printRankingTable();
break;
case "6":
worker.printScoreTableById();
break;
case "7":
worker.printScoreTableByName();
break;
case "8":
case "9":
String input = consoleTool.getUserInput();
try {
long id = Long.parseLong(input);
System.out.println(worker.searchById(id));
} catch (NumberFormatException e) {
System.out.println(worker.searchByName(input));
}
break;
case "10":
return 0;
System.out.println("Not support yet :)");
System.out.println("It will come out soon.");
break;
case "11":
System.out.println(welcomeMessage);
return 0;
worker.listRecord();
break;
case "12":
worker.printHelp();
break;
default:
return 0;
System.out.println("Don't recognize... Please enter again. (Enter 12 to show help again)");
break;
}
return 0;
}
}

@ -52,5 +52,5 @@ public class Student implements Serializable {
public static Comparator<Student> compareByName = (s1, s2) -> s1.getName().compareTo(s2.getName());
public static Comparator<Student> compareById = (s1, s2) -> (int) (s1.id - s2.id);
public static Comparator<Student> compareByGeneralScore = (s1, s2) -> s1.getGeneralScore() - s2.getGeneralScore();
public static Comparator<Student> compareByGeneralScore = (s1, s2) -> s2.getGeneralScore() - s1.getGeneralScore();
}

@ -12,9 +12,10 @@ import java.util.Map;
*/
public class ManagerTool {
private final ArrayList<Student> students;
private DataLoader dataLoader = new DataLoader();
protected ManagerTool() {
this.students = new DataLoader().load();
public ManagerTool() {
this.students = dataLoader.load();
}
public ArrayList<Student> getStudentList() {
@ -31,6 +32,8 @@ public class ManagerTool {
protected void addStudent(long id, String name, Map<String, Integer> score) {
Student student = new Student(id, name, score);
students.add(student);
dataLoader.write(students);
}
/**
@ -39,7 +42,14 @@ public class ManagerTool {
* @param id 学生idlong格式
*/
protected void removeStudent(long id) {
students.remove(getStudent(id));
Student removedStudent = this.getStudent(id);
if (removedStudent != null) {
students.remove(removedStudent);
System.out.println("Removed: " + id);
}
dataLoader.write(students);
}
/**
@ -48,7 +58,14 @@ public class ManagerTool {
* @param name 学生姓名long格式
*/
protected void removeStudent(String name) {
students.remove(getStudent(name));
Student removedStudent = this.getStudent(name);
if (removedStudent != null) {
students.remove(removedStudent);
System.out.println("Removed: " + name);
}
dataLoader.write(students);
}
/**

@ -16,6 +16,10 @@ public class StudentManager {
this.students = managerTool.getStudentList();
}
public boolean hasStudent() {
return !students.isEmpty();
}
/**
* 增添学生输入的字符串格式应为 [id] [name] ...[subjectName,score]
* 23333333 Lag English,100 Math,99 History,98
@ -24,10 +28,14 @@ public class StudentManager {
*/
public void addStudent(String input) {
String[] split = input.split(" ");
try {
long id = Long.parseLong(split[0]);
String name = split[1];
if (managerTool.getStudent(id) != null && managerTool.getStudent(name) != null) {
return;
}
HashMap<String, Integer> score = new HashMap<>();
String[] scoreInput;
for (int i = 2; i < split.length; i++) {
@ -36,6 +44,10 @@ public class StudentManager {
}
managerTool.addStudent(id, name, score);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
@ -43,7 +55,7 @@ public class StudentManager {
*
* @param id 学生idlong格式
*/
protected void removeStudent(long id) {
public void removeStudent(long id) {
managerTool.removeStudent(id);
}
@ -52,7 +64,7 @@ public class StudentManager {
*
* @param name 学生姓名long格式
*/
protected void removeStudent(String name) {
public void removeStudent(String name) {
managerTool.removeStudent(name);
}
@ -96,7 +108,7 @@ public class StudentManager {
HashMap<String, Integer> scores = new HashMap<>();
for (String subject : subjects) {
scores.put(subject, getSubjectScore(subject));
scores.put(subject, this.getSubjectScore(subject));
}
return scores;
@ -112,12 +124,22 @@ public class StudentManager {
HashMap<String, Float> scores = new HashMap<>();
for (String subject : subjects) {
scores.put(subject, getSubjectAvgScore(subject));
scores.put(subject, this.getSubjectAvgScore(subject));
}
return scores;
}
/**
* 获取某学生总成绩
*
* @param student 欲获取的学生
* @return 该学生所有科目总成绩
*/
public int getStudentGeneralScore(Student student) {
return student.getGeneralScore();
}
/**
* 获取所有科目
*
@ -132,19 +154,21 @@ public class StudentManager {
*
* @return 名次表字符串
*/
public String generateRankingTable() {
StringBuilder stringBuilder = new StringBuilder("Ranking | Name | General Score\n");
public ArrayList<String> generateRankingTable() {
ArrayList<String> rankingTable = new ArrayList<>();
ArrayList<Student> sortStudentList = managerTool.getSortedStudentList(ManagerTool.SORT_COMPARE_BY_GENERAL_SCORE);
for (int i = 0; i < sortStudentList.size(); i++) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder
.append(i + 1).append(" | ")
.append(sortStudentList.get(i).getName()).append(" | ")
.append(students.get(i).getGeneralScore())
.append('\n');
.append(students.get(i).getGeneralScore());
rankingTable.add(stringBuilder.toString());
}
return stringBuilder.toString();
return rankingTable;
}
/**
@ -152,19 +176,15 @@ public class StudentManager {
*
* @return 成绩表字符串
*/
public String generateScoreTableById() {
StringBuilder stringBuilder = new StringBuilder("ID | Name | General Score | Subject1: score Subject2: score ...\n");
public ArrayList<String> generateScoreTableById() {
ArrayList<String> scoreTable = new ArrayList<>();
ArrayList<Student> sortStudentList = managerTool.getSortedStudentList(ManagerTool.SORT_COMPARE_BY_ID);
for (Student student : sortStudentList) {
stringBuilder
.append(student.getId()).append(" | ")
.append(student.getName()).append(" | ")
.append(student.getGeneralScore()).append(" | ")
.append(listScore(student)).append('\n');
scoreTable.add(this.getStudentInfo(student));
}
return stringBuilder.toString();
return scoreTable;
}
/**
@ -172,17 +192,30 @@ public class StudentManager {
*
* @return 成绩表字符串
*/
public String generateScoreTableByName() {
StringBuilder stringBuilder = new StringBuilder("Name | Id | General Score | Subject1: score Subject2: score ...\n");
public ArrayList<String> generateScoreTableByName() {
ArrayList<String> scoreTable = new ArrayList<>();
ArrayList<Student> sortStudentList = managerTool.getSortedStudentList(ManagerTool.SORT_COMPARE_BY_NAME);
for (Student student : sortStudentList) {
scoreTable.add(this.getStudentInfo(student));
}
return scoreTable;
}
/**
* 获取学生信息条目
*
* @param student 欲获取学生
* @return 学生信息
*/
public String getStudentInfo(Student student) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder
.append(student.getName()).append(" | ")
.append(student.getId()).append(" | ")
.append(student.getGeneralScore()).append(" | ")
.append(listScore(student)).append('\n');
}
.append(student.getName()).append(" | ")
.append(this.getStudentGeneralScore(student)).append(" | ")
.append(listScore(student));
return stringBuilder.toString();
}
@ -200,48 +233,83 @@ public class StudentManager {
for (String subject : subjects) {
stringBuilder
.append(subject).append(": ")
.append(student.getScore().get(subject)).append(' ');
.append(student.getScore().get(subject)).append(" ");
}
return stringBuilder.toString();
}
/**
* 列出所有科目的成绩信息包括总分平均分
*
* @return 信息字符串
*/
public String listAllSubjectScore() {
StringBuilder stringBuilder = new StringBuilder();
ArrayList<String> subjects = getSubjects();
public ArrayList<String> generateAllSubjectInfo() {
ArrayList<String> subjects = this.getSubjects();
ArrayList<String> record = new ArrayList<>();
for (String subject : subjects) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder
.append(subject).append(" | General Score: ")
.append(this.getSubjectScore(subject)).append(" | Avg Score: ")
.append(this.getSubjectAvgScore(subject)).append('\n');
.append(this.getSubjectAvgScore(subject));
record.add(stringBuilder.toString());
}
return stringBuilder.toString();
return record;
}
/**
* 生成总的学生及科目成绩信息
*
* @return 信息字符串
*/
public String generateAllInformation() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder
.append("------------------------------------")
.append(" All Student Information ")
.append("------------------------------------").append('\n')
.append(this.generateScoreTableByName()).append('\n')
.append("------------------------------------")
.append(" All Subject Information ")
.append("------------------------------------").append('\n')
.append(this.listAllSubjectScore());
.append("------------------------------------\n")
.append(" All Student Information \n")
.append("------------------------------------\n");
ArrayList<String> studentTable = this.generateScoreTableByName();
for (String record : studentTable) {
stringBuilder.append(record).append('\n');
}
stringBuilder
.append("------------------------------------\n")
.append(" All Subject Information \n")
.append("------------------------------------\n");
ArrayList<String> subjectTable = this.generateAllSubjectInfo();
for (String record : subjectTable) {
stringBuilder.append(record).append('\n');
}
return stringBuilder.toString();
}
}
public ArrayList<Student> getStudents() {
return students;
}
/**
* 通过名字获取学生
*
* @param name 学生姓名
* @return 学生类
*/
public Student getStudent(String name) {
return managerTool.getStudent(name);
}
/**
* 通过学号获取学生
*
* @param id 学号
* @return 学生类
*/
public Student getStudent(long id) {
return managerTool.getStudent(id);
}
}

@ -1,5 +1,17 @@
package me.lensfrex.manager.utils;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Console {
public String getUserInput() {
BufferedReader command = new BufferedReader(new InputStreamReader(System.in));
try {
return command.readLine();
} catch (Exception e) {
e.printStackTrace();
return "null";
}
}
}

@ -2,10 +2,7 @@ package me.lensfrex.manager.utils;
import me.lensfrex.manager.data.Student;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.io.*;
import java.util.ArrayList;
/**
@ -20,17 +17,19 @@ public class DataLoader {
* @return 加载读取的结果若文件不存在或读取过程中发生错误则返回一个空的ArrayList
*/
public ArrayList<Student> load() {
File historyFile = new File(DATA_FILE);
File file = new File(DATA_FILE);
try {
if (!historyFile.exists()) {
historyFile.getParentFile().mkdirs();
historyFile.createNewFile();
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
return new ArrayList<>();
}
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(historyFile));
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
ArrayList<Student> list = (ArrayList<Student>) ois.readObject();
ois.close();
return (ArrayList<Student>) ois.readObject();
return list;
} catch (EOFException e) {
System.out.println("Data file is empty.");
return new ArrayList<>();
@ -40,4 +39,18 @@ public class DataLoader {
return new ArrayList<>();
}
}
public void write(ArrayList<Student> studentList) {
File file = new File(DATA_FILE);
try {
if (!file.exists()) {
file.createNewFile();
}
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
oos.writeObject(studentList);
oos.close();
} catch (Exception e) {
System.out.println("Error in writing data file:" + e);
}
}
}

@ -0,0 +1,150 @@
package me.lensfrex.manager.utils;
import me.lensfrex.manager.Main;
import me.lensfrex.manager.data.Student;
import me.lensfrex.manager.data.manager.StudentManager;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
public class Worker {
public static final String helpMessage = IOUtil.inputStreamToString(Main.class.getResourceAsStream("/me.lensfrex.manager/helpMessage.txt"), StandardCharsets.UTF_8);
public static final String studentInformationExample = IOUtil.inputStreamToString(Main.class.getResourceAsStream("/me.lensfrex.manager/studentInformationExample.txt"), StandardCharsets.UTF_8);
private final StudentManager studentManager = new StudentManager();
public Worker() {
printHelp();
if (!studentManager.hasStudent()) {
System.out.println("It's seems that there's no any student. Please add at least one student to let the program work properly.");
}
}
/**
* 打印操作信息
*/
public void printHelp() {
System.out.println(helpMessage);
}
/**
* 根据用户输入添加学生
*
* @param userInput 输入的学生信息格式参见 @studentInformationExample
*/
public void addStudent(String userInput) {
studentManager.addStudent(userInput);
System.out.println("[System]: Done. (Maybe?)");
}
/**
* 按名字删除某个学生
*
* @param name 学生名字
*/
public void removeStudent(String name) {
studentManager.removeStudent(name);
System.out.println("[System]: Done. (Maybe?)");
}
/**
* 按学号删除某个学生
*
* @param id 学生学号
*/
public void removeStudent(long id) {
studentManager.removeStudent(id);
System.out.println("[System]: Done. (Maybe?)");
}
/**
* 输出每门课程的总成绩及平均分
*/
public void printAllSubjectInfo() {
ArrayList<String> table = studentManager.generateAllSubjectInfo();
for (String record : table) {
System.out.println(record);
}
}
/**
* "输出每个学生的学号、姓名、各科考试成绩、总分、平均分,以及每门课程的总分和平均分"
*/
public void listRecord() {
System.out.println(studentManager.generateAllInformation());
}
/**
* 计算每个学生的总分
*/
public void printAllStudentScoreInfo() {
ArrayList<Student> students = studentManager.getStudents();
System.out.println("- All student general score:");
StringBuilder stringBuilder = new StringBuilder();
for (Student student : students) {
stringBuilder
.append(student.getName()).append(": ")
.append(studentManager.getStudentGeneralScore(student)).append('\n');
}
System.out.println(stringBuilder);
}
/**
* 按每个学生的总分由高到低排出名次表
*/
public void printRankingTable() {
System.out.println("----------------------------------");
System.out.println("Ranking | Name | General Score");
System.out.println("----------------------------------");
ArrayList<String> table = studentManager.generateRankingTable();
for (String record : table) {
System.out.println(record);
}
}
/**
* 按学号由小到大排出成绩表
*/
public void printScoreTableById() {
System.out.println("---------------------------------------------------------------------");
System.out.println("ID | Name | General Score | Subject1: score Subject2: score ...");
System.out.println("---------------------------------------------------------------------");
ArrayList<String> table = studentManager.generateScoreTableById();
for (String record : table) {
System.out.println(record);
}
}
/**
* 按姓名的字典顺序排出成绩表
*/
public void printScoreTableByName() {
System.out.println("---------------------------------------------------------------------");
System.out.println("ID | Name | General Score | Subject1: score Subject2: score ...");
System.out.println("---------------------------------------------------------------------");
ArrayList<String> table = studentManager.generateScoreTableByName();
for (String record : table) {
System.out.println(record);
}
}
/**
* 通过学号查找学生
*/
public String searchById(long id) {
return studentManager.getStudentInfo(studentManager.getStudent(id));
}
/**
* 通过名字查找学生
*/
public String searchByName(String name) {
return studentManager.getStudentInfo(studentManager.getStudent(name));
}
}

@ -0,0 +1,19 @@
****************************************************************
Welcome to StudentManager-S
****************************************************************
Do you want to:
1. Input record
2. Remove a student (by name or id)
3. Calculate total and average score of every course
4. Calculate total and average score of every student
5. Sort in descending order by total score of every student
6. Sort in ascending order by number
7. Sort in ascending order by name
8. Search by number
9. Search by name
10. Statistic analysis for every course (not featured yet)
11. List record
12. Show help again
0. Exit
****************************************************************
Please enter your choice:

@ -1,4 +1,7 @@
- Please enter the student information following this format:
[id] [name] ...[subjectName,score]
- Example:
23333333 LagSeeing English,100 Math,99 History,98
2333 LagSeeing English,100 Math,99 History,98
- You can enter a student each line
- Enter ":wq" to finish information recording

@ -1,18 +0,0 @@
****************************************************************
Welcome to StudentManager-S
****************************************************************
Do you want to:
1. Input record
2. Calculate total and average score of every course
3. Calculate total and average score of every student
4. Sort in descending order by total score of every student
5. Sort in ascending order by number
6. Sort in ascending order by name
7. Search by number
8. Search by name
9. Statistic analysis for every course
10. List record
11. Show help again
0. Exit
****************************************************************
Please enter your choice:
Loading…
Cancel
Save