文章目录

  • 视图
    • 欢迎界面
    • 登陆界面
    • 主菜单界面
    • 考试规则界面
    • 考试界面
  • 控制台
    • 数据控制台
    • 界面控制台
  • 服务端
    • 服务端接口
    • 服务端实现类
    • 自定义异常
  • 实体类
    • 用户
    • 考题
    • 考题信息
    • 考试信息
  • 主界面
  • 总结

视图

欢迎界面

package com.zzxx.exam.ui;import javax.swing.*;
import javax.swing.border.LineBorder;
import java.awt.*;/*** 闪屏*/
public class WelcomeWindow extends JWindow {public WelcomeWindow() {init();}private void init() {setSize(430, 300);JPanel pane = new JPanel(new BorderLayout());ImageIcon ico = new ImageIcon(getClass().getResource("pic/welcome.png"));JLabel l = new JLabel(ico);pane.add(BorderLayout.CENTER, l);pane.setBorder(new LineBorder(Color.GRAY));setContentPane(pane);setLocationRelativeTo(null);}
}

登陆界面

package com.zzxx.exam.ui;import com.zzxx.exam.entity.ClientContext;import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;/*** 登录界面 是一个具体窗口框*/
public class LoginFrame extends JFrame {private static final long serialVersionUID = 1L;private ClientContext clientContext;public LoginFrame() {init();}/*** 初始化界面组件和布局的*/private void init() {this.setTitle("登录系统");JPanel contentPane = createContentPane();this.setContentPane(contentPane);// 必须先设大小后居中setSize(300, 220);setLocationRelativeTo(null);setDefaultCloseOperation(EXIT_ON_CLOSE);this.addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) {}});}private JPanel createContentPane() {JPanel p = new JPanel(new BorderLayout());p.setBorder(new EmptyBorder(8, 8, 8, 8));p.add(BorderLayout.NORTH, new JLabel("登录考试系统", JLabel.CENTER));p.add(BorderLayout.CENTER, createCenterPane());p.add(BorderLayout.SOUTH, createBtnPane());return p;}private JPanel createBtnPane() {JPanel p = new JPanel(new FlowLayout());JButton login = new JButton("Login");JButton cancel = new JButton("Cancel");p.add(login);p.add(cancel);getRootPane().setDefaultButton(login);login.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {//需要控制器对象clientContext.login();}});cancel.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {isExit();}});return p;}public void isExit(){int res = JOptionPane.showConfirmDialog(null, "是否退出", "警告", JOptionPane.YES_NO_OPTION);if (res == JOptionPane.YES_OPTION) { // 点击“是”后执行这个代码块System.exit(0);} else {// 点击“否”后执行这个代码块return;}}private JPanel createCenterPane() {JPanel p = new JPanel(new BorderLayout());p.setBorder(new EmptyBorder(8, 0, 0, 0));p.add(BorderLayout.NORTH, createIdPwdPane());message = new JLabel("", JLabel.CENTER);p.add(BorderLayout.SOUTH, message);return p;}private JPanel createIdPwdPane() {JPanel p = new JPanel(new GridLayout(2, 1, 0, 6));p.add(createIdPane());p.add(createPwdPane());return p;}private JTextField idField;private JPanel createIdPane() {JPanel p = new JPanel(new BorderLayout(6, 0));p.add(BorderLayout.WEST, new JLabel("编号:"));JTextField idField = new JTextField();p.add(BorderLayout.CENTER, idField);this.idField = idField;return p;}/*** 简单工厂方法, 封装的复杂对象的创建过程, 返回一个对象实例*/private JPasswordField pwdField;private JPanel createPwdPane() {JPanel p = new JPanel(new BorderLayout(6, 0));p.add(BorderLayout.WEST, new JLabel("密码:"));JPasswordField pwdField = new JPasswordField();pwdField.enableInputMethods(true);p.add(BorderLayout.CENTER, pwdField);this.pwdField = pwdField;return p;}private JLabel message;public int getID() throws NumberFormatException{return Integer.parseInt(idField.getText());}public String getPasswd(){return new String(pwdField.getPassword());}public void changeMessage(String message){this.message.setText(message);}public void setClientContext(ClientContext clientContext) {this.clientContext = clientContext;}
}

主菜单界面

package com.zzxx.exam.ui;import com.zzxx.exam.entity.ClientContext;import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;/*** 主菜单界面*/
public class MenuFrame extends JFrame {private ClientContext clientContext;public MenuFrame() {init();}private void init() {setTitle("指针信息在线测评");setSize(600, 400);setContentPane(createContentPane());setLocationRelativeTo(null);setDefaultCloseOperation(EXIT_ON_CLOSE);addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) {}});}private JPanel createContentPane() {JPanel pane = new JPanel(new BorderLayout());ImageIcon icon = new ImageIcon(this.getClass().getResource("pic/title.png"));pane.add(BorderLayout.NORTH, new JLabel(icon));pane.add(BorderLayout.CENTER, createMenuPane());pane.add(BorderLayout.SOUTH, new JLabel("指针信息--版权所有 盗版必究", JLabel.RIGHT));return pane;}private JLabel info; // 记录用户的信息private JPanel createMenuPane() {JPanel pane = new JPanel(new BorderLayout());// 务必将 info 引用到界面控件对象info = new JLabel("XXX 同学您好!", JLabel.CENTER);pane.add(BorderLayout.NORTH, info);pane.add(BorderLayout.CENTER, createBtnPane());return pane;}private JPanel createBtnPane() {JPanel pane = new JPanel(new FlowLayout());JButton start = createImgBtn("pic/exam.png", "开始");JButton result = createImgBtn("pic/result.png", "分数");JButton msg = createImgBtn("pic/message.png", "考试规则");JButton exit = createImgBtn("pic/exit.png", "离开");pane.add(start);pane.add(result);pane.add(msg);pane.add(exit);getRootPane().setDefaultButton(start);start.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {clientContext.menuTostart();clientContext.changeExaminfo();}});msg.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent arg0) {clientContext.menuTomsg();clientContext.showRules();}});exit.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {isExit();}});return pane;}public void isExit(){int res = JOptionPane.showConfirmDialog(null, "是否退出", "警告", JOptionPane.YES_NO_OPTION);if (res == JOptionPane.YES_OPTION) { // 点击“是”后执行这个代码块System.exit(0);} else {// 点击“否”后执行这个代码块return;}}// 创建图片按钮的方法private JButton createImgBtn(String img, String txt) {ImageIcon ico = new ImageIcon(this.getClass().getResource(img));JButton button = new JButton(txt, ico);// button.setIcon(ico);// 设置文本相对于图标的垂直位置button.setVerticalTextPosition(JButton.BOTTOM);// 设置文本相对于图标的水平位置button.setHorizontalTextPosition(JButton.CENTER);return button;}public void changeInfo(String name){this.info.setText(name + "同学您好!");}public void setClientContext(ClientContext clientContext) {this.clientContext = clientContext;}
}

考试规则界面

package com.zzxx.exam.ui;import javax.swing.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;/*** 主菜单界面*/
public class MsgFrame extends JFrame {private JTextArea ta;public MsgFrame() {init();}private void init() {setSize(600, 400);setContentPane(createContentPane());setLocationRelativeTo(null);setDefaultCloseOperation(EXIT_ON_CLOSE);addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) {}});}private JScrollPane createContentPane() {JScrollPane jsp = new JScrollPane();ta = new JTextArea();jsp.add(ta);jsp.getViewport().add(ta);return jsp;}public void showMsg(String file) {ta.setText(file);ta.setLineWrap(true);// 允许折行显示ta.setEditable(false);// 不能够编辑内容}
}

考试界面

package com.zzxx.exam.ui;import com.zzxx.exam.entity.ClientContext;
import com.zzxx.exam.entity.QuestionInfo;import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;public class ExamFrame extends JFrame {// 选项集合, 方便答案读取的处理private Option[] options = new Option[4];private ClientContext clientContext;private ArrayList<Integer> Useroptions = new ArrayList<>();public ExamFrame() {init();}private void init() {setTitle("指针信息在线测评");setSize(600, 380);setContentPane(createContentPane());setLocationRelativeTo(null);setDefaultCloseOperation(EXIT_ON_CLOSE);this.addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) {// 正在关闭的时候}});}private JPanel createContentPane() {JPanel pane = new JPanel(new BorderLayout());pane.setBorder(new EmptyBorder(6, 6, 6, 6));ImageIcon icon = new ImageIcon(getClass().getResource("pic/exam_title.png"));pane.add(BorderLayout.NORTH, new JLabel(icon));pane.add(BorderLayout.CENTER, createCenterPane());pane.add(BorderLayout.SOUTH, createToolsPane());return pane;}private JLabel examInfo = null;private JPanel createCenterPane() {JPanel pane = new JPanel(new BorderLayout());// 注意!examInfo = new JLabel("姓名:XXX 考试:XXX 考试时间:XXX", JLabel.CENTER);pane.add(BorderLayout.NORTH, examInfo);pane.add(BorderLayout.CENTER, createQuestionPane());pane.add(BorderLayout.SOUTH, createOptionsPane());return pane;}private JPanel createOptionsPane() {JPanel pane = new JPanel();Option a = new Option(0, "A");Option b = new Option(1, "B");Option c = new Option(2, "C");Option d = new Option(3, "D");options[0] = a;options[1] = b;options[2] = c;options[3] = d;pane.add(a);pane.add(b);pane.add(c);pane.add(d);return pane;}private JScrollPane createQuestionPane() {JScrollPane pane = new JScrollPane();pane.setBorder(new TitledBorder("题目"));// 标题框// 注意!questionArea = new JTextArea();questionArea.setText("问题\nA.\nB.");questionArea.setLineWrap(true);// 允许折行显示questionArea.setEditable(false);// 不能够编辑内容// JTextArea 必须放到 JScrollPane 的视图区域中(Viewport)pane.getViewport().add(questionArea);return pane;}private JPanel createToolsPane() {JPanel pane = new JPanel(new BorderLayout());pane.setBorder(new EmptyBorder(0, 10, 0, 10));// 注意!questionCount = new JLabel("题目:20 的第1题");timer = new JLabel("剩余时间:222秒");pane.add(BorderLayout.WEST, questionCount);pane.add(BorderLayout.EAST, timer);pane.add(BorderLayout.CENTER, createBtnPane());return pane;}private JPanel createBtnPane() {JPanel pane = new JPanel(new FlowLayout());prev = new JButton("上一题");next = new JButton("下一题");JButton send = new JButton("交卷");pane.add(prev);pane.add(next);pane.add(send);for (Option o:options) {o.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {if(o.isSelected()){Useroptions.add(o.value);}else{try{Useroptions.remove(o.value);}catch (IndexOutOfBoundsException ex){}}}});}prev.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {//保存选项clientContext.SaveAnswers();//跳转到下一题if(clientContext.getCurrentQuestionNumber()>0){clientContext.setCurrentQusetionNumber(clientContext.getCurrentQuestionNumber()-1);clientContext.ChanegQuestion();}//清空选项for (int i = 0; i < options.length; i++) {options[i].setSelected(false);}//恢复选项recoverChose();}});next.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {//保存选项clientContext.SaveAnswers();//跳转到下一题if(clientContext.getCurrentQuestionNumber()<19){clientContext.setCurrentQusetionNumber(clientContext.getCurrentQuestionNumber()+1);clientContext.ChanegQuestion();}//清空选项for (int i = 0; i < options.length; i++) {options[i].setSelected(false);}//恢复选项recoverChose();}});send.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {showUserscore(clientContext.ExamOver());}});return pane;}public void showUserscore(Integer score){int res = JOptionPane.showConfirmDialog(null, "是否提交试卷", "是否继续", JOptionPane.YES_NO_OPTION);if (res == JOptionPane.YES_OPTION) { // 点击“是”后执行这个代码块int sc = JOptionPane.showConfirmDialog(null, "您的成绩是:"+String.valueOf(score)+"分", "成绩", JOptionPane.PLAIN_MESSAGE);System.exit(0);} else {// 点击“否”后执行这个代码块return;}}/*** 使用内部类扩展了 JCheckBox 增加了val 属性, 代表答案值*/class Option extends JCheckBox{int value;public Option(int val, String txt) {super(txt);this.value = val;}public void setValue(int i){this.value = i;}@Overridepublic String toString(){return String.valueOf(this.value);}}private JTextArea questionArea;private JButton next;private JButton prev;private JLabel questionCount;private JLabel timer;public void TimerGoing(long h, long m, long s) {String time = h + ":" + m + ":" + s;if (m < 5) {timer.setForeground(new Color(0xC85848));} else {timer.setForeground(Color.blue);}timer.setText(time);}public void changeExamInfo(String title,String name,int time){this.examInfo.setText("姓名:"+name + " 考试:"+title+ " 考试时间:"+time+"秒");}public void recoverChose(){List<Integer> list = new ArrayList<>();setOptionValue((ArrayList<Integer>) clientContext.getQuesInfo().getUserAnswers());list.addAll(Useroptions);for (int i = 0; i < list.size(); i++) {options[list.get(i)].setSelected(true);}}public long[] caculateTime(Integer time){long[] hms = new long[3];hms[0] = time/3600;hms[1] = (time - hms[0]*3600) / 60;hms[2] = time - hms[0]*3600 - hms[1]*60;return hms;}public void ChanegeQuestionArea(String q){this.questionArea.setText(q);}public void ChangeQuestionCount(Integer num){this.questionCount.setText("题目:20 的第"+ num +"题");}public void setClientContext(ClientContext clientContext) {this.clientContext = clientContext;}public List<Integer> getOptionValue(){ArrayList<Integer> ans = new ArrayList<>();for (Integer o:Useroptions) {ans.add(o);}return ans;}public void setOptionValue(ArrayList<Integer> list){this.Useroptions.removeAll(Useroptions);this.Useroptions.addAll(list);}
}

控制台

数据控制台

package com.zzxx.exam.entity;import com.zzxx.exam.util.Config;import java.io.*;
import java.util.*;/*** 实体数据管理, 用来读取数据文件放到内存集合当中*/
public class EntityContext {private Config config;//null,必须通过set方法注入[程序开启后]//储存所有用户的集合private Map<Integer,User> Users = new HashMap<>();//储存所有试题的集合//20道,每个难度2道private Map<Integer, Question> Questions = new HashMap<>();private ArrayList<String> rules = new ArrayList<>();private ArrayList<QuestionInfo> questionInfos = new ArrayList<>();public EntityContext(Config config){this.config=config;try {LoadUsers(config);} catch (IOException e) {e.printStackTrace();}try {LoadQuestions(config);} catch (IOException|NumberFormatException e) {e.printStackTrace();}try {readRules(config);} catch (IOException e) {e.printStackTrace();}}/*读取user.txt文件解析成user对象并储存*/private void LoadUsers(Config config) throws IOException {System.out.println("读用户文件");BufferedReader br = null;try {br = new BufferedReader(new InputStreamReader(new FileInputStream(config.getString("UserFile"))));} catch (FileNotFoundException e) {e.printStackTrace();}while(true){String str = null;try {str = br.readLine();} catch (IOException e) {e.printStackTrace();}if (str == null) {break;}else if(str.startsWith("#")){continue;}else if(str.equals("")){continue;}else{String[] ss = str.split(":");Users.put(Integer.parseInt(ss[0]),new User(ss[1],Integer.parseInt(ss[0]),ss[2]));}}br.close();}/*读取corejava.txt文件解析成Question对象并储存*/private void LoadQuestions(Config config) throws IOException {System.out.println("读题目文件");ArrayList<Question> questionArrayList = new ArrayList<>();BufferedReader br = null;try {br = new BufferedReader(new InputStreamReader(new FileInputStream(config.getString("QuestionFile"))));} catch (FileNotFoundException e) {e.printStackTrace();}int id = 0;String sb = null;do {id++;String title = null;// 题干List<String> options = new ArrayList<String>();// 若干选项List<Integer> answers = new ArrayList<Integer>();// 正确答案int score = 0;// 分数int level = 0;// 难度级别int type = 0; // 类型: 单选 SINGLE_SELECTION /多选 MULTI_SELECTIONfor (int i = 0; i < 6; i++) {try {sb = br.readLine();} catch (IOException e) {e.printStackTrace();}if (i == 0) {if(sb == null) break;String[] str1 = sb.split(",");//截取第一次for (int j = 0; j < str1.length; j++) {if(j == 0){String[] str2 = str1[j].split("=");//截取正确答案String[] str3 = str2[str2.length-1].split("/");for (int k = 0; k < str3.length; k++) {//放正确答案answers.add(Integer.parseInt(str3[k]));}}else if(j == 1) {//放分数String[] str2 = str1[j].split("=");score = Integer.parseInt(str2[1]);}else if(j == 2){//放难度指数String[] str2 = str1[j].split("=");level = Integer.parseInt(str2[1]);}}}else if (i == 1) {title = sb;} else {options.add(sb);}}if (answers.size() == 1) {type = 0;} else {type = 1;}Question question = new Question(id, title,options, answers,score, level,type);Questions.put(id,question);} while (sb!=null);br.close();//读取rules文件}private void readRules(Config config) throws IOException{System.out.println("读规则文件");BufferedReader br = null;try {br = new BufferedReader(new InputStreamReader(new FileInputStream(config.getString("ExamRule"))));} catch (FileNotFoundException e) {e.printStackTrace();}String sb = null;while(true){sb = br.readLine();if(sb == null) {break;}rules.add(sb);}br.close();}//生成随机20道 每个难度2道public List<QuestionInfo> loadQuestionInfo(){List<Question> list = new ArrayList<>();int[] level = new int[11];for (int i = 1; i < level.length; i++) {level[i] = 0;}Collection<Question> set =Questions.values();Iterator it = set.iterator();int i = 0;while(it.hasNext()){list.add((Question) it.next());}int num = 0;boolean[] isExist = new boolean[62];for (boolean b:isExist) {b = false;}while(num<20){Question question = list.get((int) (Math.random()*61));if(level[question.getLevel()]<2 && isExist[question.getId()] == false){isExist[question.getId()] = true;questionInfos.add(new QuestionInfo(num+1,question));System.out.println(question.getId());num++;level[question.getLevel()]++;}}return questionInfos;}public void setConfig(Config config) {this.config = config;}public User getUserById(int id){return this.Users.get(id);}public ArrayList<String> getRules(){return this.rules;}public Integer getTimelimit(){return config.getInt("TimeLimit")*3600;}public Integer getQuestionCount(){return config.getInt("QuestionNumber");}public String getTitle(){return config.getString("PaperTitle");}
}

界面控制台

package com.zzxx.exam.entity;import com.zzxx.exam.service.ExamService;
import com.zzxx.exam.service.ExamServiceImpl;
import com.zzxx.exam.service.IdOrPwdException;
import com.zzxx.exam.ui.*;import javax.swing.*;
import javax.swing.text.html.Option;
import java.util.*;
import java.util.Timer;/*
前端控制器,管理/控制所有界面*/
public class ClientContext {private WelcomeWindow welcomeWindow;private LoginFrame loginFrame;private MenuFrame menuFrame;private MsgFrame msgFrame;private ExamFrame examFrame;private ExamServiceImpl examServiceImpl;private EntityContext entityContext;private int id =0;private String passwd = null;private Integer currentQuestionNumber = 0;//欢迎界面显示,一定时间后消失,登陆界面显示public void show(){this.welcomeWindow.setVisible(true);Timer timer = new Timer();timer.schedule(new TimerTask() {@Overridepublic void run() {welcomeWindow.setVisible(false);loginFrame.setVisible(true);}},1500);}//登录public void login() throws NumberFormatException{//1、收集数据/*要获取loginFrame的id和passwordloginFrame提供一个对外的方法*///2、调用业务模型ExamService的login方法try {id = loginFrame.getID();passwd = loginFrame.getPasswd();}catch (NumberFormatException e){loginFrame.changeMessage("输错了");}catch (RuntimeException e){loginFrame.changeMessage("出错啦");}catch (Exception e){loginFrame.changeMessage("就是错了");}//3、try-catch决定界面的跳转和显示//try - 登陆成功 - 跳转//catch - 登录失败,显示信息try {examServiceImpl.login(id,passwd);loginFrame.setVisible(false);menuFrame.setVisible(true);} catch (IdOrPwdException e) {loginFrame.changeMessage(e.getMessage());} catch (NumberFormatException e){loginFrame.changeMessage("输错了");}catch (RuntimeException e){loginFrame.changeMessage("出错啦");}catch (Exception e){loginFrame.changeMessage("就是错了");}this.menuChangeName();}//主菜单界面换名字public void menuChangeName(){try{menuFrame.changeInfo(entityContext.getUserById(id).getName());}catch (NullPointerException e){}}//显示考试规则public void showRules(){msgFrame.showMsg(examServiceImpl.getMsg());}//从主菜单道考试规则界面public void menuTomsg(){menuFrame.setVisible(false);msgFrame.setVisible(true);Timer timer = new Timer();timer.schedule(new TimerTask() {@Overridepublic void run() {menuFrame.setVisible(true);msgFrame.setVisible(false);}},3000);//显示一定时间后,返回主菜单}//从主菜单道考试界面public void menuTostart(){menuFrame.setVisible(false);examFrame.setVisible(true);}//更改考试界面的相关信息public void changeExaminfo(){ExamInfo start = examServiceImpl.start();final Integer[] time = {start.getTimeLimit()};examFrame.changeExamInfo(start.getTitle(),start.getUser().getName(),start.getTimeLimit());examFrame.ChanegeQuestionArea(examServiceImpl.getQuestion(currentQuestionNumber).toString());Runnable runnable = new Runnable() {long[] hms = new long[3];@Overridepublic void run() {while(time[0] > 0) {hms = examFrame.caculateTime(time[0]-1);examFrame.TimerGoing(hms[0] , hms[1] , hms[2]);time[0] = time[0] -1;try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}}};Thread t1 = new Thread(runnable);t1.start();}//切换上一题和下一题public void ChanegQuestion(){examFrame.ChanegeQuestionArea(examServiceImpl.getQuestion(currentQuestionNumber).toString());examFrame.ChangeQuestionCount(currentQuestionNumber+1);}//保存用户选择的选项public void SaveAnswers(){examServiceImpl.saveUserAnswers(currentQuestionNumber,examFrame.getOptionValue());}//考试结束public Integer ExamOver(){return examServiceImpl.examOver();}public void setWelcomeWindow(WelcomeWindow welcomeWindow) {this.welcomeWindow = welcomeWindow;}public void setLoginFrame(LoginFrame loginFrame) {this.loginFrame = loginFrame;}public void setMenuFrame(MenuFrame menuFrame) {this.menuFrame = menuFrame;}public void setMsgFrame(MsgFrame msgFrame) {this.msgFrame = msgFrame;}public void setExamFrame(ExamFrame examFrame) {this.examFrame = examFrame;}public void setEntityContext(EntityContext entityContext) {this.entityContext = entityContext;}public void setExamServiceImpl(ExamServiceImpl examServiceImpl) {this.examServiceImpl = examServiceImpl;}public int getID() {return id;}public String getPasswd() {return passwd;}public void setCurrentQusetionNumber(Integer num){this.currentQuestionNumber = num;}public Integer getCurrentQuestionNumber(){return currentQuestionNumber;}public QuestionInfo getQuesInfo(){return examServiceImpl.getQuestion(currentQuestionNumber);}
}

服务端

服务端接口

package com.zzxx.exam.service;import java.util.List;import com.zzxx.exam.entity.ExamInfo;
import com.zzxx.exam.entity.QuestionInfo;
import com.zzxx.exam.entity.User;/** 软件的核心功能:登陆,开始(发卷),交卷... */
public interface ExamService {// login方法没有修饰词,不是默认的,在接口里所有方法都是公有的User login(int id, String pwd) throws IdOrPwdException;ExamInfo start();QuestionInfo getQuestion(int index);void saveUserAnswers(int index, List<Integer> userAnswers);int examOver();String getMsg();}

服务端实现类

package com.zzxx.exam.service;import com.zzxx.exam.entity.*;
import com.zzxx.exam.ui.LoginFrame;import java.util.ArrayList;
import java.util.List;public class ExamServiceImpl implements ExamService{private List<QuestionInfo> paper = new ArrayList<>();private Integer UserScore = 0;private EntityContext entityContext;private ClientContext clientContext;private LoginFrame loginFrame;@Overridepublic User login(int id, String pwd) throws IdOrPwdException {User user = entityContext.getUserById(id);if(user == null){throw new IdOrPwdException("用户不存在");}else if(!pwd.equals(user.getPassword())){throw new IdOrPwdException("密码错误");}else return user;}@Overridepublic ExamInfo start() {//1、生产试卷,定义一个集合 paper<QuestionInfo> 来存储试卷题目ExamInfo examInfo = new ExamInfo(entityContext.getTitle(), entityContext.getUserById(clientContext.getID()), entityContext.getTimelimit(), entityContext.getQuestionCount());paper.addAll(entityContext.loadQuestionInfo());return examInfo;}@Override//获取题目public QuestionInfo getQuestion(int index) {return paper.get(index);}//保存答案@Overridepublic void saveUserAnswers(int index, List<Integer> userAnswers) {this.getQuestion(index).setUserAnswers(userAnswers);}//交卷@Overridepublic int examOver() {clientContext.SaveAnswers();int num = 0;for (QuestionInfo q:paper) {boolean flag = true;ArrayList<Integer> userAns = new ArrayList<>();ArrayList<Integer> Ans = new ArrayList<>();userAns.addAll(this.getQuestion(num).getUserAnswers());Ans.addAll(this.getQuestion(num).getQuestion().getAnswers());if((Ans.retainAll(userAns))||(userAns.retainAll(Ans))){flag = false;}if(flag){this.setUserScore(this.getUserScore()+this.getQuestion(num).getQuestion().getScore());}num++;}return UserScore;}@Overridepublic String getMsg() {StringBuilder sb = new StringBuilder();for (String ss:entityContext.getRules()) {sb.append(ss + "\n");}return sb.toString();}public void setEntityContext(EntityContext entityContext) {this.entityContext = entityContext;}public void setLoginFrame(LoginFrame loginFrame) {this.loginFrame = loginFrame;}public void setClientContext(ClientContext clientContext) {this.clientContext = clientContext;}public Integer getUserScore() {return UserScore;}public void setUserScore(Integer userScore) {UserScore = userScore;}
}

自定义异常

package com.zzxx.exam.service;public class IdOrPwdException extends Exception {private static final long serialVersionUID = 1L;public IdOrPwdException() {}public IdOrPwdException(String message) {super(message);}public IdOrPwdException(Throwable cause) {super(cause);}public IdOrPwdException(String message, Throwable cause) {super(message, cause);}}

实体类

用户

package com.zzxx.exam.entity;import java.io.Serializable;
import java.util.Objects;// entity 实体, 就是业务范畴中的具体名词
public class User implements Serializable {private int id;private String name;private String password;private String phone;private String email;public User() {super();}public User(String name, int id, String password ) {super();this.name = name;this.id = id;this.password = password;}public int getId() {return id;}public String getName() {return name;}public String getPassword() {return password;}public void setId(int id) {this.id = id;}public void setName(String name) {this.name = name;}public void setPassword(String password) {this.password = password;}public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}public String getPhone() {return phone;}public void setPhone(String phone) {this.phone = phone;}@Overridepublic String toString() {return name;}@Overridepublic boolean equals(Object o) {if (this == o) return true;if (o == null || getClass() != o.getClass()) return false;User user = (User) o;return id == user.id;}@Overridepublic int hashCode() {return Objects.hash(id);}
}

考题

package com.zzxx.exam.entity;import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;/*** Question对象代表一道试题。* 包含题干和四个选项以及正确答案** @author Bonnie*/
public class Question implements Serializable {// 难度级别 1~10public static final int LEVEL1 = 1;public static final int LEVEL2 = 2;public static final int LEVEL3 = 3;public static final int LEVEL4 = 4;public static final int LEVEL5 = 5;public static final int LEVEL6 = 6;public static final int LEVEL7 = 7;public static final int LEVEL8 = 8;public static final int LEVEL9 = 9;public static final int LEVEL10 = 10;// 单选题public static final int SINGLE_SELECTION = 0;// 多选题public static final int MULTI_SELECTION = 1;private int id;private String title;// 题干private List<String> options = new ArrayList<String>();// 若干选项private List<Integer> answers = new ArrayList<Integer>();// 正确答案private int score;// 分数private int level;// 难度级别private int type; // 类型: 单选 SINGLE_SELECTION /多选 MULTI_SELECTIONpublic Question() {}public Question(int id, String title, List<String> options, List<Integer> answers, int score, int level, int type) {this.id = id;this.title = title;this.options = options;this.answers = answers;this.score = score;this.level = level;this.type = type;}public int getId() {return id;}public void setId(int id) {this.id = id;}public List<Integer> getAnswers() {return answers;}public List<String> getOptions() {return options;}public void setOptions(List<String> options) {this.options = options;}public String getTitle() {return title;}public void setAnswers(List<Integer> answers) {this.answers = answers;}public void setTitle(String title) {this.title = title;}public int getLevel() {return level;}public void setLevel(int level) {this.level = level;}public int getScore() {return score;}public void setScore(int score) {this.score = score;}public int getType() {return type;}public void setType(int type) {this.type = type;}public String toString() {StringBuffer sb = new StringBuffer("问题:"+title + "\n");for (int i = 0; i < options.size(); i++) {sb.append((char) (i + 'A') + "." + options.get(i) + "\n");}sb.append("\n");return sb.toString();}@Overridepublic boolean equals(Object o) {if (this == o) return true;if (o == null || getClass() != o.getClass()) return false;Question question = (Question) o;return id == question.id;}@Overridepublic int hashCode() {return Objects.hash(id);}
}

考题信息

package com.zzxx.exam.entity;import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;/*** 问题和用户答案的值对象,* 表示界面上的一道题和对应的用户答案* 是值对象** @author Bonnie*/
public class QuestionInfo implements Serializable {// 考题private Question question;// 在试卷(paper)中的序号 0,1,2private int questionIndex;// 用户答案private List<Integer> userAnswers = new ArrayList<Integer>();public QuestionInfo() {}public QuestionInfo(int questionIndex, Question question) {this.question = question;this.questionIndex = questionIndex;}public QuestionInfo(int questionIndex, Question question, List<Integer> userAnswers) {super();this.question = question;this.userAnswers = userAnswers;this.questionIndex = questionIndex;}public Question getQuestion() {return question;}public void setQuestion(Question question) {this.question = question;}public List<Integer> getUserAnswers() {return userAnswers;}public void setUserAnswers(List<Integer> userAnswers) {this.userAnswers = userAnswers;}public int getQuestionIndex() {return questionIndex;}public void setQuestionIndex(int questionIndex) {this.questionIndex = questionIndex;}@Overridepublic String toString() {return this.getQuestion().toString();}
}

考试信息

package com.zzxx.exam.entity;import java.io.Serializable;/*** 考试信息值对象. 是值对象** @author Bonnie*/
public class ExamInfo implements Serializable {// 考试科目private String title;// 考生private User user;// 分钟为单位private int timeLimit;// 题目数量private int questionCount;public ExamInfo() {}public ExamInfo(String title, User user, int timeLimit, int questionCount) {super();this.title = title;this.user = user;this.timeLimit = timeLimit;this.questionCount = questionCount;}@Overridepublic String toString() {if (user == null)return "无信息!";return "姓名: " + user.getName() + ", 编号: " + user.getId() +", 考试时间: " + timeLimit + "分钟" + ", 考试科目: "+ title + ", 题目数量: " + questionCount;}public String getTitle() {return title;}public void setTitle(String title) {this.title = title;}public User getUser() {return user;}public void setUser(User user) {this.user = user;}public int getTimeLimit() {return timeLimit;}public void setTimeLimit(int timeLimit) {this.timeLimit = timeLimit;}public int getQuestionCount() {return questionCount;}public void setQuestionCount(int questionCount) {this.questionCount = questionCount;}
}

主界面

package com.zzxx.exam.ui;import com.zzxx.exam.entity.ClientContext;
import com.zzxx.exam.entity.EntityContext;
import com.zzxx.exam.service.ExamServiceImpl;
import com.zzxx.exam.util.Config;public class Main {public static void main(String[] args) {//创建所有对象WelcomeWindow welcomeWindow = new WelcomeWindow();LoginFrame loginFrame = new LoginFrame();MenuFrame menuFrame = new MenuFrame();MsgFrame msgFrame = new MsgFrame();ExamFrame examFrame = new ExamFrame();Config config = new Config("config.properties");ClientContext clientContext = new ClientContext();EntityContext entityContext = new EntityContext(config);ExamServiceImpl examService = new ExamServiceImpl();//所有依赖关系的注入clientContext.setLoginFrame(loginFrame);clientContext.setWelcomeWindow(welcomeWindow);clientContext.setExamFrame(examFrame);clientContext.setMsgFrame(msgFrame);clientContext.setMenuFrame(menuFrame);clientContext.setExamServiceImpl(examService);clientContext.setEntityContext(entityContext);loginFrame.setClientContext(clientContext);menuFrame.setClientContext(clientContext);examFrame.setClientContext(clientContext);examService.setEntityContext(entityContext);examService.setLoginFrame(loginFrame);examService.setClientContext(clientContext);//程序开始clientContext.show();}
}

总结

 本次小项目的制作还是很有收获的,特别是对MVC思想的理解。
完整包:考试系统

【Java实战小项目】考试系统相关推荐

  1. java吃货联盟系统源码_小项目,吃货联盟,java初级小项目,源代码

    小项目,吃货联盟,java初级小项目,源代码 1importjava.util.Scanner;23/**4* 吃货联盟订餐管理系统5*6*/7publicclassOrderingMsg {8pub ...

  2. 基于JAVA供电公司安全生产考试系统计算机毕业设计源码+数据库+lw文档+系统+部署

    基于JAVA供电公司安全生产考试系统计算机毕业设计源码+数据库+lw文档+系统+部署 基于JAVA供电公司安全生产考试系统计算机毕业设计源码+数据库+lw文档+系统+部署 本源码技术栈: 项目架构:B ...

  3. Java选择题简单的考试系统

    Java选择题简单的考试系统 做前声明: 此系统包括了Java中:面向对象-封装.String-StringBuilder.ArrayList集合.继承-抽象-final.static-接口-多态.四 ...

  4. Java web小项目_个人主页(1)—— 云环境搭建与项目部署

    摘自:Java web小项目_个人主页(1)-- 云环境搭建与项目部署 作者:丶PURSUING 发布时间: 2021-03-26 23:59:39 网址:https://blog.csdn.net/ ...

  5. 基于Java Web的在线考试系统的实现

    摘  要 随着互联网的发展,教育的方式逐渐步入信息化.智能化,网络教育逐渐成为教育未来发展的重要趋势,在线考试系统成为教育成果考察的主流方向.在线考试充分利用现代信息化技术的优势,使考试更方便.更高效 ...

  6. 毕业设计 - 基于java web的在线考试系统【源码+论文】

    文章目录 前言 一.项目设计 1. 模块设计 2. 基本功能 2.1 登录功能 2.2 系统答题 2.3 答题得分 2.4 错题解析 3. 实现效果 二.部分源码 项目源码 前言 今天学长向大家分享一 ...

  7. 基于java web的在线考试系统(源码+论文)

    今天介绍的一个项目是, 基于java web的在线考试系统 1 设计内容及要求 1.1 在线考试系统概述 基于Java web开发的在线考试系统不仅可以充分利用校园内各种资源,对学校的各种教学资源进行 ...

  8. 基于JAVA四六级在线考试系统计算机毕业设计源码+数据库+lw文档+系统+部署

    基于JAVA四六级在线考试系统计算机毕业设计源码+数据库+lw文档+系统+部署 基于JAVA四六级在线考试系统计算机毕业设计源码+数据库+lw文档+系统+部署 本源码技术栈: 项目架构:B/S架构 开 ...

  9. java基础小项目_java基础小项目练习之1----3天做出飞机大战

    Shoot射击游戏第一天 一.关键问题(理论): 1.简述FlyingObject.Enemy.Award.Airplane.Bee.Bullet.Hero之间的继承与实现关系 2.简述Hero类构造 ...

  10. java毕业生设计-在线考试系统-计算机源码+系统+mysql+调试部署+lw

    java毕业生设计-在线考试系统-计算机源码+系统+mysql+调试部署+lw java毕业生设计-在线考试系统-计算机源码+系统+mysql+调试部署+lw 本源码技术栈: 项目架构:B/S架构 开 ...

最新文章

  1. poj_2479 动态规划
  2. 与自定义词典 分词_如何掌握分词技术,你需要学会这些
  3. 华为存储S58000T-硬盘更换
  4. VS2008中自定义C++工程模板与修改新建文件默认编码的办法
  5. 算法:串联所有单词的子串
  6. 这35个Java代码优化细节,你用了吗?
  7. kubernetes集群使用GPU及安装kubeflow1.0.RC操作步骤
  8. python-计算机二级考试-报考笔记
  9. 前端—每天5道面试题(十二)
  10. 数据清洗 excel mysql_Excel获取MYSQL数据库数据
  11. Unity中实现3D拾取功能及其原理
  12. GHGL项目总结-TIPS系统和银行拨付
  13. 云运维拓扑图_云平台网络拓扑图
  14. 用python画一朵鲜艳欲滴的红玫瑰
  15. 用devc++表白_「你表白,我宠你」520—实验猿的表白日,小析姐的“宠粉”节
  16. [Android]小米5刷root过程记录
  17. 刘强东在耶鲁北京中心演讲(2015-8):商城+金融+3农+生鲜
  18. web系统快速开发_开发一个快速销售系统
  19. ([\s\S]*?)正则表达式写法
  20. 如何防止数据泄密和丢失?22项安全策略,守护企业数据安全

热门文章

  1. 三菱 FX5U PLC 4轴程序。 控制松下伺服3个, 步进电机一个, 四轴自动堆垛码垛设备程序, 回原点动作用专用的原点回归指令写的
  2. Unity3dC#分布式游戏服务器ET框架介绍-组件式设计
  3. JAVA死磕系列 疯狂创客圈
  4. HTML朗读可以用英文吗,关于英语朗读的方法技巧
  5. 通信协议晦涩难懂搞不定?看完这些动图恍然大悟
  6. Redis imgrate迁移键 (error) ERR Target instance replied with error: NOAUTH Authentication required.
  7. 如何用串口助手测试软件485通讯功能,串口调试助手如何检测RS485端口好坏及信号发送的好坏?...
  8. BZOJ5287 HNOI2018毒瘤
  9. 支付宝APP参数SDK转换URL网页链接
  10. 基于核的黎曼编码和字典学习