java编程实现素数环_结对编程(JAVA实现)
項目成員:黃思揚(3117004657)、劉嘉媚(3217004685)
二、PSP表格
PSPPersonal Software Process Stages預估耗時(分鐘)實際耗時(分鐘)
Planning
計劃
60
40
· Estimate
· 估計這個任務需要多少時間
60
40
Development
開發
1440
1505
· Analysis
· 需求分析
30
15
· Design Spec
· 生成設計文檔
20
15
· Design Review
· 設計復審
30
15
· Coding Standard
· 代碼規范
20
20
· Design
· 具體設計
80
80
· Coding
· 具體編碼
900
980
· Code Review
· 代碼復審
30
30
· Test
· 測試(自我測試,修改代碼,提交修改)
330
400
Reporting
報告
130
100
· Test Report
· 測試報告
80
60
· Size Measurement
· 計算工作量
30
20
· Postmortem & Process Improvement Plan
· 事后總結, 并提出過程改進計劃
30
20
合計
1630
1695
三、效能分析
由于之前采用單線程執行,在文件IO流的處理上花費了不少的時間,包括代碼上的執行存在部分冗余,代碼上可以提高利用率。打開了線程池以后,多線程執行,大大提高了執行速度,在代碼邏輯改進優化后,對大量生成題目的效果十分顯著,由30s時間完成優化到2s:
四、設計過程
(一)流程圖
視圖設計過程:
生成題目設計過程:
判斷對錯設計過程:
(二)項目目錄:
分包思路:
1)視圖層:view?包含主頁面與兩個功能頁面
2)實體類:po? 包含題目存放類Deposit、ChildDeposit,分數處理類
3)邏輯處理層:service? 處理題目生成等的邏輯、處理題目判錯的邏輯
4)工具類:util?包含文件的讀寫功能
(三)總體實現思路
程序運行,進入主頁面,點擊選擇進入相應功能頁面(生成題目or判斷對錯),如果為生成題目,用戶需要輸入相關參數(題目數量、數的大小范圍),視圖層獲取輸入的數據,傳入至邏輯層中進行處理,先判斷輸入是否有誤,有誤則終止程序,無誤則調用題目生成的方法CreateAth;如果為判斷對錯,用戶需要選擇相應的文件(Exersises.txt和Answers.txt),視圖層獲取輸入的數據,傳入到邏輯層進行處理,判斷輸入無誤后,調用題目判錯的方法Judge。
題目生成的思路:題目要求生成的算術運算符少于3個,先隨機生成一個運算符的個數,傳入到CreateAth方法中,先生成一個根結點即算術運算符,然后隨機生成在左右子樹小于總運算符個數的運算符個數,同時生成運算符,當生成運算符個數為0,則生成葉子結點即運算操作數,左右子樹也是重復上述過程。把生成的算式放在一個動態數組里面,每當生成一個算式,就去檢查里面是否包含這個算式,如果重復就去掉,達到查重的目的。
判斷對錯的思路:使用readfile讀取Exersises.txt文件內容,使用正則表達式分割開題目的序號和算式,算式是中綴表達式的表示方式,通過build方法把算式改為前綴表達式,如:1 + (( 2 + 3)* 4 ) – 5,轉換成前綴則為- + 1 * + 2 3 4 5,計算其答案,讀取Answers.txt的內容,使用正則表達式分割開題目的序號和答案,根據兩個文件的序號,對比答案是否相同,如果相同則記錄對的題目的數量,和題目序號,寫出到Correction.txt文件。
(四)細節實現思路
1)如何保證基本的數值運算,確定參數的范圍?
自然數的數值之間的運算可簡單實現,但是自然數、真分數、帶分數之間的運算之間的格式需要自己設計的,并且題目要求“如果存在形如e1÷ e2的子表達式,那么其結果應是真分數”,經過討論之后,決定把所有數據統一當成分數來處理,整數的分母則為1,在運算的過程中把分子與分母獨立出來分別操作加減乘除運算,到最后再進行約分等化簡處理。
2)怎么生成算式并且查重?
生成的算式要求不能產生負數、生成的題目不能重復,且即任何兩道題目不能通過有限次交換+和×左右的算術表達式變換為同一道題目,經過討論,決定使用二叉樹來實現,由于二叉樹的運算次序是孩子結點的運算次序要優先于根結點的,所以使用非葉子節點存放運算符,葉子結點存放數值,可以解決前后符號之間的優先級別關系,解決括號的添加問題,當父母結點的算術符優先級高于右孩子結點的算術運算符時,左右都要加括號,當相等時,則右孩子樹要加括號;出現了負數時,交換左右子樹即可;此外,解決了查重的復雜度問題,開始的方案想采用遍歷的方式來達到查重,現只需要判斷兩棵樹是否相同即可。
五、程序關鍵代碼
從頁面獲取到數據,進行處理:
packageservice;importjava.util.HashMap;importjava.util.Map;public classEntryJudge{public booleanEntry(String[] args){//向主頁面返回的運行成功與否的標志
boolean tag = false;//判斷用戶輸入是否正確
if(args.length == 0 || args.length % 2 != 0) {
tag= false;returntag;
}//取出參數
Map params =checkParams(args);//執行相應處理
CreateAth opera = newCreateAth(params);
Judge check= newJudge(params);if(params.containsKey("-e")&¶ms.containsKey("-a")){
check.Judge();
tag= true;returntag;
}else if(params.containsKey("-n") || params.containsKey("-r") || params.containsKey("-d")) {
opera.createAth();
tag= true;returntag;
}returntag;
}private MapcheckParams(String[] args) {
Map params = new HashMap<>();for (int i = 0; i < args.length; i = i + 2) {
params.put(args[i], args[i+1]);
}returnparams;
}
}
EntryJudge
題目生成邏輯處理:
packageservice;importcom.sun.org.apache.xalan.internal.xsltc.compiler.util.StringStack;importpo.Deposit;importpo.Fraction;importutil.FileUtil;importpo.ChildDeposit;importjava.util.ArrayList;importjava.util.List;importjava.util.Map;importjava.util.Stack;importjava.util.concurrent.ExecutorService;importjava.util.concurrent.Executors;importjava.util.concurrent.ThreadLocalRandom;importjava.util.concurrent.TimeUnit;/*** 生成題目類*/
public classCreateAth{private int maxNum = 100; //生成題目的整數最大值
private int denArea = 20; //分母的范圍
private int maxCount = 10;//生成題目數量
privateDeposit content;private static final String[] SYMBOLS = newString[]{"+", "-", "x", "\u00F7"};/*** 生成隨機題目,初始化,把主類中輸入的參數內容調進來*/
public CreateAth(Mapparams) {for(String str : params.keySet()) {if (str.equals("-n")) {
maxCount=Integer.valueOf(params.get(str));
}else if (str.equals("-r")) {
maxNum=Integer.valueOf(params.get(str));
}else if (str.equals("-d")) {
denArea=Integer.valueOf(params.get(str));
}
}
}/*** 生成題目*/
private ExecutorService executor =Executors.newCachedThreadPool();public voidcreateAth() {
StringBuilder exercises= newStringBuilder();
StringBuilder answers= newStringBuilder();
List list = new ArrayList<>();long start =System.currentTimeMillis();for (int i = 1; i <=maxCount;) {
CreateAth generate= new CreateAth(true);if (!list.contains(generate)){
String[] strs= generate.print().split("=");
exercises.append(i).append(". ").append(strs[0]).append("\n");
answers.append(i).append(".").append(strs[1]).append("\n");
list.add(generate);
i++;
}
}
executor.execute(()-> FileUtil.writeFile(exercises.toString(), "Exercises.txt"));
executor.execute(()-> FileUtil.writeFile(answers.toString(), "Answers.txt"));
executor.shutdown();long end =System.currentTimeMillis();try{boolean loop = true;while(loop) {
loop= !executor.awaitTermination(30, TimeUnit.SECONDS); //超時等待阻塞,直到線程池里所有任務結束
} //等待所有任務完成
System.out.println("生成的" + maxCount + "道題和答案存放在當前目錄下的Exercises.txt和Answers.txt,耗時為:"+(end - start) + "ms");
}catch(InterruptedException e) {
e.printStackTrace();
}
}
——————以下是生成題目所調用到的方法———————————/*** 生成組成題目隨機數
* area:分母的范圍*/
private int random(intarea) {
ThreadLocalRandom random=ThreadLocalRandom.current();int x =random.nextInt(area);if (x == 0) x = 1;returnx;
}/*** ThreadLocalRandom類在多線程環境中生成隨機數。
* nextBoolean()?方法用于從隨機數生成器的序列返回下一個偽隨機的,均勻分布的布爾值*/
private booleanrandomBoolean() {
ThreadLocalRandom random=ThreadLocalRandom.current();returnrandom.nextBoolean();
}/*** 把生成的每個數進行處理得出分子分母*/
privateFraction creator() {if(randomBoolean()) {return new Fraction((random(maxNum)), 1);
}else{if(randomBoolean()) {int den =random(denArea);int mol = random(den *maxNum);return newFraction(den, mol);
}else{int den =random(denArea);return newFraction(random(den), den);
}
}
}/*** 單步計算
*@paramsymbol 符號
*@paramleft 左
*@paramright 右
*@return得出來結果后經過約分的分數*/
privateFraction calculate(String symbol, Fraction left, Fraction right) {switch(symbol) {case "+":returnleft.add(right);case "-":returnleft.subtract(right);case "x":returnleft.multiply(right);default:returnleft.divide(right);
}
}/*** 隨機生成一道四則運算題目
*@paramfractionNum 運算符個數
*@return二叉樹*/
private Deposit build(intfractionNum){if(fractionNum == 0){return new Deposit(creator(),null,null);
}
ThreadLocalRandom random=ThreadLocalRandom.current();
ChildDeposit node= new ChildDeposit(SYMBOLS [random.nextInt(4)],null, null);//左子樹運算符數量
int left =random.nextInt(fractionNum);//右子樹運算符數量
int right = fractionNum - left - 1;
node.setLeft(build(left));
node.setRight(build(right));
Fraction value=calculate(node.getSymbol(),node.getLeft().getValue(),node.getRight().getValue());//負數處理
if(value.Negative()){//交換左右子樹,就是交換兩個減數的順序
if (node != null) {
Deposit swap=node.getLeft();
node.setLeft(node.getRight());
node.setRight(swap);
}
value=calculate(node.getSymbol(),node.getLeft().getValue(),node.getRight().getValue());
}
node.setValue(value);returnnode;
}/*** 獲取表達式,
* 打印題目與答案*/
privateString print(){return print(content) + " = " +content.getValue();
}privateString print(Deposit node){if (node == null){return "";
}
String frac=node.toString();
String left=print(node.getLeft());if (node.getLeft() instanceof ChildDeposit && node instanceofChildDeposit) {if(bracketsLeft(((ChildDeposit) node.getLeft()).getSymbol(), ((ChildDeposit) node).getSymbol())) {
left= "(" + " " + left + " " + ")";
}
}
String right=print(node.getRight());if (node.getRight() instanceof ChildDeposit && node instanceofChildDeposit) {if(bracketsRight(((ChildDeposit) node.getRight()).getSymbol(), ((ChildDeposit) node).getSymbol())) {
right= "(" + " " + right + " " + ")";
}
}return left + frac +right;
}/*** 比較兩個符號誰優先級更高,子樹的箱號優先級低要加括號,左括號or右括號*/
private booleanbracketsLeft(String left,String mid){return (left.equals("+")|| left.equals("-")) && (mid.equals("x")||mid.equals("\u00F7"));
}private booleanbracketsRight(String right, String mid){return (right.equals("+")|| right.equals("-")) && (mid.equals("x")||mid.equals("\u00F7"))||(mid.equals("\u00F7"))||(mid.equals("-")&&(mid.equals("+")|| mid.equals("-")));
}/***生成一個題目,先調用下面的createAth方法來判斷有沒有生成一個用build方法生成的樹*/CreateAth(booleanisBuild){if(isBuild){
ThreadLocalRandom random=ThreadLocalRandom.current();int kind = random.nextInt(4);if (kind == 0) kind = 1;
content=build(kind);while(content.getValue().Zero()){
content=build(kind);
}
}
}/*** 查重*/@Overridepublic booleanequals(Object o) {if (this == o) return true;if (!(o instanceof CreateAth)) return false;
CreateAth exercise=(CreateAth) o;returncontent.equals(exercise.content);
}
Fraction getResult() {returncontent.getValue();
}
——————以下是判斷題目所要調用到的方法———————————/*** 中綴表達式生成樹,用棧的特點,把中綴表達式變成前綴表達式
* 在判錯中調用
*@paramexercise 中綴表達式
*@return二叉樹*/Deposit build(String exercise) {
String[] strs= exercise.trim().split(" "); //拿走標號
Stack depositStack = new Stack<>(); //結點棧
StringStack symbolStack = new StringStack(); //符號棧//中綴表達式轉換成前綴表達式,然后再用前序遍歷生成數
for (int i = strs.length - 1; i >= 0; i--) {
String str=strs[i];if (!str.matches("[()+\\u00F7\\-x]")) {
depositStack.push(new Deposit(newFraction(str)));
}else{//符號結點
while (!symbolStack.empty() && ((symbolStack.peekString().equals("x") ||symbolStack.peekString().equals("\u00F7"))&& (str.equals("+") || str.equals("-"))|| str.equals("("))) {
String symbol=symbolStack.popString();if (symbol.equals(")")) {break;
}
push(symbol, depositStack);
}if (str.equals("(")) {continue;
}
symbolStack.pushString(str);
}
}while (!symbolStack.empty()) {
push(symbolStack.popString(), depositStack);
}this.content =depositStack.pop();returncontent;
}/*** 將符號壓入節點棧且計算結果,僅在生成前綴表達式*/
private void push(String symbol, StacknodeStack) {
Deposit left=nodeStack.pop();
Deposit right=nodeStack.pop();
ChildDeposit node= newChildDeposit(symbol, left, right);
node.setValue(calculate(symbol, left.getValue(), right.getValue()));
nodeStack.push(node);
}
}
CreateAth
題目判錯處理:判斷答案的正確性,并記錄下來正確題目與錯誤題目序號,打印到Grade.txt
packageservice;importpo.Fraction;importutil.FileUtil;importjava.util.ArrayList;importjava.util.List;importjava.util.Map;/*** 答案判錯類*/
public classJudge{private int trueNum; //正確數目
private int wrongNum; //錯誤數目
private String exerciseFileName; //題目文件名
private String answerFileName; //答案文件名
public Judge(Mapparams) {for(String str : params.keySet()) {if (str.equals("-e")) {
exerciseFileName=params.get(str);
}else if (str.equals("-a")) {
answerFileName=params.get(str);
}
}
}/*** 判斷錯誤 ,并把錯誤寫入文件*/
public voidJudge() {long start =System.currentTimeMillis();
List correctNums = new ArrayList<>();
List wrongNums = new ArrayList<>();
FileUtil.readFile((exercise, answer)->{
String[] strs1= exercise.split("\\."); //匹配每一行
String[] strs2 = answer.split("\\.");if (strs1[0].equals(strs2[0])) {
CreateAth exes= new CreateAth(false);
exes.build(strs1[1].trim()); //去掉兩端的空格后,將后綴表達式生成樹變成前綴的,
if (exes.getResult().equals(new Fraction(strs2[1].trim()))) { //答案兩邊都相等,繼續執行下面的
correctNums.add(strs1[0]);
trueNum++;
}else{
wrongNums.add(strs1[0]);
wrongNum++;
}
}
}, exerciseFileName, answerFileName);
FileUtil.writeFile(printResult(correctNums, wrongNums),"Correction.txt");long end =System.currentTimeMillis();
System.out.println("題目答案對錯統計存在當前目錄下的Correction.txt文件下,耗時為:" + (end - start) + "ms");
}private String printResult(List correctNums, ListwrongNums) {
StringBuilder builder= newStringBuilder();
builder.append("Correct: ").append(trueNum).append(" (");for (int i = 0; i < correctNums.size(); i++) {if (i == correctNums.size() - 1) {
builder.append(correctNums.get(i));break;
}
builder.append(correctNums.get(i)).append(", ");
}
builder.append(")").append("\n");
builder.append("Wrong: ").append(wrongNum).append(" (");for (int i = 0; i < wrongNums.size(); i++) {if (i == wrongNums.size() - 1) {
builder.append(wrongNums.get(i));break;
}
builder.append(wrongNums.get(i)).append(", ");
}
builder.append(")").append("\n");returnbuilder.toString();
}
}
Judge
分數處理類:把所有隨機生成的數都當成是分數處理,同時在些定義分數的四則運算方法
packagepo;/*** 1. 把所有隨機生成的數都當成是分數處理(解決了自然整數,分數,帶分數之間的差異)
* 2. 定義了分數的四則運算類*/
public classFraction{private int mol; //分子
private int den; //分母
/*** 處理隨機生成的數值(約分等),組合分數對象*/
public Fraction(int mol, intden) {this.mol =mol;this.den =den;if (den <= 0) {throw new RuntimeException("分數分母不能為0");
}//否則就進行約分
int mod = 1;int max = den > mol ?den : mol;for (int i = 1; i <= max; i++) {if (mol % i == 0 && den % i == 0) {
mod=i;
}
}this.mol = mol /mod;this.den = den /mod;
}/*** 處理隨機生成的數值,這個用于分解分數對象(僅在判錯中使用)*/
publicFraction(String str) {int a = str.indexOf("'");int b = str.indexOf("/");if (a != -1) {//取出數組,轉換類型
int c = Integer.valueOf(str.substring(0, a));
den= Integer.valueOf(str.substring(b + 1));
mol= c * den + Integer.valueOf(str.substring(a + 1, b));
}else if (b != -1) {
String[] sirs= str.split("/");
mol= Integer.valueOf(sirs[0]);
den= Integer.valueOf(sirs[1]);
}else{
mol=Integer.valueOf(str);
den= 1;
}
}/*** 定義加減乘除類,返回值類型(全都當成分數處理),由于要返回這個類的內容,所以方法前要加類名*/
publicFraction add(Fraction fraction) {return new Fraction(this.mol * fraction.den + this.den * fraction.mol, this.den *fraction.den);
}publicFraction subtract(Fraction fraction) {return new Fraction(this.mol * fraction.den - this.den * fraction.mol, this.den *fraction.den);
}publicFraction multiply(Fraction fraction) {return new Fraction(this.mol * fraction.mol, this.den *fraction.den);
}publicFraction divide(Fraction fraction) {return new Fraction(this.mol * fraction.den, this.den *fraction.mol);
}
}
Fraction
題目實現存放類以及其子類:
packagepo;importjava.util.Objects;/*** 用于存放題目的類,用二叉樹的形式*/
public classDeposit{privateDeposit left;privateDeposit right;private Fraction value; //用于二叉樹結點的是符號與運算結果數值的之間的變化
publicDeposit(Fraction value, Deposit left, Deposit right){this.value =value;this.left =left;this.right =right;
}/*** 取結點數據*/
publicFraction getValue() {returnvalue;
}publicDeposit getRight(){returnright;
}publicDeposit getLeft(){returnleft;
}/*** 設置結點數據*/
publicDeposit(Fraction value){this.value =value;
}public voidsetLeft(Deposit left){this.left =left;
}public voidsetRight(Deposit right){this.right =right ;
}public voidsetValue(Fraction value) {this.value =value;
}
@OverridepublicString toString() {returnvalue.toString();
}/*** 用于查重,判斷二棵樹是否相同*/@Overridepublic booleanequals(Object o) {if (this == o) return true;if (!(o instanceof Deposit)) return false;
Deposit node=(Deposit) o;return Objects.equals(value, node.value) &&Objects.equals(left, node.left)&&Objects.equals(right, node.right);
}
}
—————————————————————————————————————分割線——————————————————————————————————————————————packagepo;/*** 用于記錄符號結點,與Deposit類是一樣的道理*/
public class ChildDeposit extendsDeposit{privateString symbol;publicChildDeposit(String symbol, Deposit left, Deposit right){super(null, left, right);this.symbol =symbol;
}publicString getSymbol() {returnsymbol;
}
@OverridepublicString toString() {return " " + symbol + " ";
}/*** 用于查重*/@Overridepublic booleanequals(Object o) {if (this == o) return true;if (!(o instanceof ChildDeposit)) return false;
ChildDeposit that=(ChildDeposit) o;boolean flag = this.symbol != null &&symbol.equals(that.symbol);if(!flag) return false;boolean left = this.getLeft() != null &&getLeft().equals(that.getLeft());boolean right = this.getRight() != null &&getRight().equals(that.getRight());//左右子樹相同
if(left &&right) {return true;
}if(left ^right) {return false;
}//如果是加法或乘法由于滿足交換律所以要判斷
if(this.symbol.equals("+") || this.symbol.equals("x")) {
left= this.getLeft() != null &&getLeft().equals(that.getRight());
right= this.getRight() != null &&getRight().equals(that.getLeft());
}return left &&right;
}
}
Deposit,ChildDeposit
文件讀寫工具類:處理文件的寫入與讀出
packageutil;import java.io.*;public classFileUtil{/*** 寫入文件中*/
public static voidwriteFile(String content, String fileName) {
File file= newFile(fileName);try (BufferedWriter bw = new BufferedWriter(newFileWriter(file))){if(!file.exists()){
file.createNewFile();
}
bw.write(content);
bw.flush();
}catch(IOException e) {
System.out.println("文件操作失敗...");
}
}/*** 讀文件內容
*@paramcallBack 回調接口,分別處理每一行
*@paramexerciseFileName 題目文件
*@paramanswerFileName 答案文件*/
public static voidreadFile(ReaderCallBack callBack, String exerciseFileName, String answerFileName) {
File exerciseFile= newFile(exerciseFileName);
File answerFile= newFile(answerFileName);if(!exerciseFile.exists() || !answerFile.exists()) {
System.out.println("文件不存在!");return;
}try (BufferedReader br1 = new BufferedReader(newFileReader(exerciseFileName));
BufferedReader br2= new BufferedReader(newFileReader(answerFileName))) {
String line1, line2;while ((line1 = br1.readLine()) != null && (line2 = br2.readLine()) != null) {
callBack.deal(line1, line2);
}
}catch(IOException e) {
System.out.println("讀取文件失敗!");
}
}public interfaceReaderCallBack {void deal(String exercise, String answer) throwsIOException;
}
}
FileUtil
圖形界面:
MainView :主頁面,用戶在兩種操作中選一進行
packageview;import javax.swing.*;import java.awt.*;importjava.awt.event.ActionEvent;importjava.awt.event.ActionListener;public classMainView {public static voidmain(String[] args) {newMainJFrame();
}
}class MainJFrame extendsJFrame {/*** 程序主界面*/
private static final long serialVersionUID = 1;//定義全局變量
privateJLabel title;privateJButton generate,judge;privateJLabel result;private JPanel down = newJPanel();//創建一個容器
Container ct;
MainJFrame(){
ct=this.getContentPane();this.setLayout(null);//設置容器為空布局,絕對定位//標題
title= new JLabel("四則運算題目生成程序");
title.setFont(new Font("微軟雅黑",Font.BOLD, 30));
title.setBounds(140, 40, 340, 100);//生成
generate = new JButton("生成題目");
generate.setBounds(120, 220, 140, 40);
generate.addActionListener(newgenerateListener());//判錯
judge = new JButton("判斷對錯");
judge.setBounds(300, 220, 140, 40);
judge.addActionListener(newjudgeListenner());//添加組件
ct.add(title);
ct.add(generate);
ct.add(judge);
ct.add(down);this.setTitle("MyApp");this.setSize(600, 450);//設置窗口大小
this.setLocationRelativeTo(null);//基本設置 把窗口位置設置到屏幕中心
this.setVisible(true);//顯示窗口
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //關閉窗口 當點擊窗口的關閉按鈕時退出程序(沒有這一句,程序不會退出)
}class generateListener implementsActionListener {//監聽生成按鈕點擊事件
public voidactionPerformed(ActionEvent e) {newGenerateView();
}
}class judgeListenner implementsActionListener{//監聽判錯按鈕點擊事件
public voidactionPerformed(ActionEvent e) {newJudgeView();
}
}
}
MainView
GenerateView:用戶輸入參數范圍、生成題目的頁面
packageview;importservice.EntryJudge;import javax.swing.*;import java.awt.*;importjava.awt.event.ActionEvent;importjava.awt.event.ActionListener;public class GenerateView extendsJFrame {privateJLabel title,result;privateJButton confirm;privateJLabel subjectNum,intArea,denArea;privateJTextField subjectNumField,intAreaField,denAreaField;private JPanel down = newJPanel();publicGenerateView() {//創建一個容器
Container ct;
ct=this.getContentPane();//this.setLayout(null);//設置容器為空布局,絕對定位
this.setSize(600, 450);//基本設置
this.setLocationRelativeTo(null);this.setLayout(null);
title= new JLabel("生成題目");
title.setFont(new Font("微軟雅黑",Font.BOLD, 20));
title.setBounds(200,20,280,60);//生成題目數
subjectNum = new JLabel("請輸入生成題目數:");
subjectNum.setFont(new Font("微軟雅黑",Font.BOLD, 16));
subjectNum.setBounds(70,100,160,50);
subjectNumField= new JTextField (10);
subjectNumField.setBounds(260,100,260,40);//整數范圍
intArea = new JLabel("請輸入整數范圍:");
intArea.setFont(new Font("微軟雅黑",Font.BOLD, 16));
intArea.setBounds(70,150,160,50);
intAreaField= new JTextField (20);
intAreaField.setBounds(260,150,260,40);//分母范圍
denArea = new JLabel("請輸入分數分母的范圍:");
denArea.setFont(new Font("微軟雅黑",Font.BOLD, 16));
denArea.setBounds(70,200,180,50);
denAreaField= new JTextField (20);
denAreaField.setBounds(260,200,260,40);
confirm= new JButton("確定");
confirm.setBounds(250,270, 60, 50);
confirm.addActionListener(newConfirmActionListener());//設置底部panel
down.setBounds(130, 330, 280, 50);//設置底部panel背景透明
down.setBackground(null);
down.setOpaque(false);
result= newJLabel();
result.setFont(new Font("微軟雅黑",Font.BOLD, 18));//添加組件
down.add(result);
ct.add(title);
ct.add(subjectNum);
ct.add(subjectNumField);
ct.add(intArea);
ct.add(intAreaField);
ct.add(denArea);
ct.add(denAreaField);
ct.add(confirm);
ct.add(down);this.setVisible(true);//顯示窗口
this.setLocationRelativeTo(null);//基本設置 把窗口位置設置到屏幕中心
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); //關閉窗口
}class ConfirmActionListener implementsActionListener {public voidactionPerformed(ActionEvent e) {
String args1=subjectNumField.getText();
String args2=intAreaField.getText();
String args3=denAreaField.getText();
String [] args= new String[]{"-n",args1,"-r",args2,"-d",args3};
EntryJudge ej= newEntryJudge();boolean res =ej.Entry(args);//獲取命令執行結果
if(res == true) {
result.setText("結果:生成題目成功");
}else{
result.setText("結果:生成題目失敗");
}
}
}
}
GenerateView
JudegeView:用戶選擇文件,是判斷對錯的頁面
packageview;importservice.EntryJudge;import javax.swing.*;import java.awt.*;importjava.awt.event.ActionEvent;importjava.awt.event.ActionListener;public class JudgeView extendsJFrame {privateJLabel title,result;privateJButton confirm;privateJLabel subjectNum,intArea,file1,file2;privateJButton btn1,btn2;private JPanel down = newJPanel();publicJudgeView() {//創建一個容器
Container ct;
ct=this.getContentPane();this.setSize(600, 450);//基本設置
this.setLocationRelativeTo(null);this.setLayout(null);
title= new JLabel("判斷對錯");
title.setFont(new Font("微軟雅黑",Font.BOLD, 20));
title.setBounds(200,20,280,60);//生成題目數
subjectNum = new JLabel("請選擇題目文件:");
subjectNum.setFont(new Font("微軟雅黑",Font.BOLD, 16));
subjectNum.setBounds(70,100,160,50);
btn1= new JButton ("選擇文件");
btn1.setBounds(240,100,120,40);
btn1.addActionListener(newChooseFile1ActionListener());
file1= newJLabel();
file1.setFont(new Font("微軟雅黑",Font.BOLD, 14));
file1.setBounds(390,100,130,50);//整數范圍
intArea = new JLabel("請輸入答案文件:");
intArea.setFont(new Font("微軟雅黑",Font.BOLD, 16));
intArea.setBounds(70,150,160,50);
btn2= new JButton ("選擇文件");
btn2.setBounds(240,150,120,40);
btn2.addActionListener(newChooseFile2ActionListener());
file2= newJLabel();
file2.setFont(new Font("微軟雅黑",Font.BOLD, 14));
file2.setBounds(390,150,130,50);
confirm= new JButton("確定");
confirm.setBounds(250,270, 60, 50);
confirm.addActionListener(newConfirmActionListener());//設置底部panel
down.setBounds(130, 330, 280, 50);//設置底部panel背景透明
down.setBackground(null);
down.setOpaque(false);
result= newJLabel();
result.setFont(new Font("微軟雅黑",Font.BOLD, 18));//添加組件
down.add(result);
ct.add(title);
ct.add(subjectNum);
ct.add(btn1);
ct.add(file1);
ct.add(intArea);
ct.add(btn2);
ct.add(file2);
ct.add(confirm);
ct.add(down);this.setVisible(true);//顯示窗口
this.setLocationRelativeTo(null);//基本設置 把窗口位置設置到屏幕中心
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); //關閉窗口
}class ChooseFile1ActionListener implementsActionListener {public voidactionPerformed(ActionEvent e) {
JFileChooser chooser= new JFileChooser(); //設置選擇器
chooser.setMultiSelectionEnabled(true); //設為多選
int returnVal = chooser.showDialog(new JLabel(),"選擇");
String filename= chooser.getSelectedFile().getName(); //獲取絕對路徑
file1.setText(filename);
}
}class ChooseFile2ActionListener implementsActionListener {public voidactionPerformed(ActionEvent e) {
JFileChooser chooser2= new JFileChooser(); //設置選擇器
chooser2.setMultiSelectionEnabled(true); //設為多選
int returnVal = chooser2.showDialog(new JLabel(),"選擇");
String filename= chooser2.getSelectedFile().getName(); //獲取絕對路徑
file2.setText(filename);
}
}class ConfirmActionListener implementsActionListener {public voidactionPerformed(ActionEvent e) {//獲取結果
String [] args = new String[]{"-e", "Exercises.txt","-a","Answers.txt"};
EntryJudge ej= newEntryJudge();boolean res =ej.Entry(args);//獲取命令執行結果
if(res == true) {
result.setText("結果:生成題目成功");
}else{
result.setText("結果:生成題目失敗");
}
}
}
}
JudegeView
六、測試測試結果
程序運行,成功打開圖形界面:
測試題目生成是否成功:
輸入相關參數,點擊確定 ,生成題目成功:
查看Exersises.txt,成功生成題目:
查看Answers.txt,答案:
測試判錯程序:
改錯二道題的答案:
打開判錯的圖形界面,選擇算式文件、選擇答案文件:
點擊確定,查看統計文件Grade.txt:
生成一萬道算式:
詳細的github地址:
部分截圖:
七、項目小結
此次的結對編程,我們均涉及了代碼的設計、編寫以及測試。討論項目的基本構思對我負責的前期編碼十分重要,從基礎數值的定義和生成,再到采用二叉樹存放算式,最后一步步完成項目,通過兩個人的討論,使得項目的整體思路變得清晰。在后期的編碼中我的伙伴對我的編程方式提出了更有條理性的建議,最終在小改動下讓整個項目的代碼變得更為整潔與條理。
多討論交流意見對編程的幫助很大,在判錯功能中,從開始的沒有頭緒,到討論出來通過應用一個棧的實例:中綴表達式轉前綴表達式,解決了判錯的問題;開始項目生成大數量題目的速度很慢,在小伙伴豐富的編程經驗下,指出了關于多線程運行程序的方式,并且通過優化一些代碼,大大提高了效率。
總結
以上是生活随笔為你收集整理的java编程实现素数环_结对编程(JAVA实现)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python 反射和动态加载_Pytho
- 下一篇: php字符长度函数漏洞 ctf,CTF中