簡單的四則運算(JAVA版) 201571030129


簡單的四則運算(JAVA版)  

GitHub項目地址:https://github.com/wangshenghai/wsh.git

 

1、需求分析

  • 程序可接收一個輸入參數n,然后隨機產生n道加減乘除練習題;
  • 每個數字在 0 和 100 之間,運算符在3個到5個之間;
  • 每個練習題至少要包含2種運算符;
  • 隨機產生的練習題在運算過程中不得出現負數與非整數,比如不能出 3/5+2=2.6,2-5+10=7等算式;
  • 練習題生成好后,將你的學號與生成的n道練習題及其對應的正確答案輸出到文件“result.txt中;
  • 不要輸出額外信息,文件目錄與程序目錄一致。
2、功能設計
  • 程序可接收一個輸入參數n,然后隨機產生n道加減乘除算術題;
  • 每個數字在 0 和 100 之間,運算符在1個到2個之間。
  • 每個練習題至少要包含1種運算符。
  • 隨機產生的算術題在運算過程中不得出現負數與非整數,比如不能出 3/5+2=2.6,2-5+10=7等算式。
  • 練習題生成好后,將你的學號與生成的n道練習題及其對應的正確答案輸出到文件“result.txt中。
  • 不要輸出額外信息,文件目錄與程序目錄一致。

 

 

3、設計實現
   下圖表示我的總體設計框架
 
4、測試運行
 

 

 

 
5、核心代碼
            轉化后綴表達式以及壓棧的操作過程, 
public class Main {  
   public int eval(String exp) throws IllegalExpressionException{  
       List<String> list = infixExpToPostExp(exp);//轉化成后綴表達式  
       return doEval(list);//真正求值  
   }  
     
   //遇到操作符壓棧,遇到表達式從后綴表達式中彈出兩個數,計算出結果,壓入堆棧  
   private int doEval(List<String> list) throws IllegalExpressionException {  
      Stack<String> stack =  new Stack<String>();  
      String element;  
      int n1,n2,result;  
      try{  
          for(int i = 0; i < list.size();i++){  
              element = list.get(i);  
              if(isOperator(element)){  
                  n1 = Integer.parseInt(stack.pop());  
                  n2 = Integer.parseInt(stack.pop());  
                  result = doOperate(n1,n2,element);  
                  stack.push(new Integer(result).toString());  
             }else{  
                 stack.push(element);  
             }  
          }  
          return Integer.parseInt(stack.pop());  
      }catch(RuntimeException e){  
          throw new IllegalExpressionException(e.getMessage());         
      }  
   }  
     
   private int doOperate(int n1, int n2, String operator) {  
      if(operator.equals("+"))  
          return n1 + n2;  
      else if(operator.equals("-"))  
          return n1 - n2;  
      else if(operator.equals("*"))  
          return n1 * n2;  
      else  
          return n1 / n2;  
   }  
  
   private boolean isOperator(String str){  
       return str.equals("+") || str.equals("-") || str.equals("*") || str.equals("/");  
   }  
     
   private List<String> infixExpToPostExp(String exp) throws IllegalExpressionException{//將中綴表達式轉化成為后綴表達式  
       List<String> postExp = new ArrayList<String>();//存放轉化的后綴表達式的鏈表  
       StringBuffer numBuffer = new StringBuffer();//用來保存一個數的  
       Stack<Character> opStack = new Stack<Character>();//操作符棧  
       char ch,preChar;  
       opStack.push('#');  
       try{  
           for(int i = 0; i < exp.length();){  
               ch = exp.charAt(i);  
               switch(ch){  
                    case '+':  
                    case '-':  
                    case '*':  
                    case '/':  
                        preChar = opStack.peek();  
//              如果棧里面的操作符優先級比當前的大,則把棧中優先級大的都添加到后綴表達式列表中  
                        while(priority(preChar) >= priority(ch)){  
                            postExp.add(""+preChar);  
                            opStack.pop();  
                            preChar = opStack.peek();  
                        }  
                        opStack.push(ch);  
                        i++;  
                        break;  
                    case '(':  
//              左括號直接壓棧  
                        opStack.push(ch);  
                        i++;  
                        break;  
                    case ')':  
//              右括號則直接把棧中左括號前面的彈出,並加入后綴表達式鏈表中  
                        char c = opStack.pop();  
                        while(c != '('){  
                            postExp.add("" + c);  
                            c = opStack.pop();  
                        }  
                        i++;  
                        break;  
//           #號,代表表達式結束,可以直接把操作符棧中剩余的操作符全部彈出,並加入后綴表達式鏈表中  
                 case '#':  
                     char c1;  
                     while(!opStack.isEmpty()){  
                         c1 = opStack.pop();  
                         if(c1 != '#')  
                           postExp.add("" + c1);  
                     }  
                     i++;  
                     break;  
                              //過濾空白符  
                 case ' ':  
                 case '\t':  
                     i++;  
                     break;  
//               數字則湊成一個整數,加入后綴表達式鏈表中  
                 default:  
                     if(Character.isDigit(ch)){  
                         while(Character.isDigit(ch)){  
                             numBuffer.append(ch);  
                             ch = exp.charAt(++i);  
                         }  
                         postExp.add(numBuffer.toString());  
                         numBuffer = new StringBuffer();  
                     }else{  
                       throw new IllegalExpressionException("illegal operator");  
                     }  
               }  
           }  
       }catch(RuntimeException e){  
           throw new IllegalExpressionException(e.getMessage());   
       }  
       return postExp;  
   }  
public static void main(String[] args) throws IllegalExpressionException 
{ Scanner scan
= new Scanner(System.in); System.out.println("請輸入題目的數量:"); int s = scan.nextInt(); ArrayList<String> ex= new ArrayList<String>(); String[] operate=new String[]{"+","-","*","/"}; Random r=new Random(); ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine se = manager.getEngineByName("js"); for(int i=0;i<s;i++) { int a=(int)(Math.random()*100); int b=(int)(Math.random()*100); int c=(int)(Math.random()*100); int q=(int)(Math.random()*2); String cz=operate[r.nextInt(4)]; String cz1=operate[r.nextInt(4)]; //if(q==0){ String AX=String.valueOf(a)+String.valueOf(cz)+String.valueOf(b); Main eval=new Main(); int result = eval.eval(AX+"#"); System.out.println(a+cz+b+"="+result); ex.add(AX+"="+result); }
try {
              File f = new File("result.txt"); 
            FileWriter fw = new FileWriter(f);
            PrintWriter pw = new PrintWriter(fw);
            pw.println("201571030129");
            pw.println();
            for(String con:ex)
             {
                    pw.println(con);  
                    
             }
            
            fw.close();
            
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

 6、總結

          做本次設計令我影響最深刻的是,做設計的時候困難重重,第一JAVA語言的基礎很薄弱,沒有很好的掌握語言以至於應用,第二做項目的時候盲目的開始寫導致在寫的過程中沒有思路,丟失的內容很多,然后改起來很麻煩,設計中沒能按要求完成,在以后的學習中繼續努力,加油!

7、PSP展示

 

PSP2.1

任務內容

計划完成需要的時間(min)

實際完成需要的時間(min)

Planning

計划

15

8

·       Estimate

·  估計這個任務需要多少時間,並規划大致工作步驟

15

8

Development

開發

485

600

··       Analysis

  需求分析 (包括學習新技術)

10

10

·       Design Spec

·  生成設計文檔

5

6

·       Design Review

·  設計復審 (和同事審核設計文檔)

5

4

·       Coding Standard

  代碼規范 (為目前的開發制定合適的規范)

10

10

·       Design

  具體設計

35

20

·       Coding

  具體編碼

240

330

·       Code Review

·  代碼復審

120

100

·       Test

·  測試(自我測試,修改代碼,提交修改)

60

80

Reporting

報告

20

30

··       Test Report

·  測試報告

3

3

·       Size Measurement

  計算工作量

2

2

·       Postmortem & Process Improvement Plan

·  事后總結 ,並提出過程改進計划

15

25

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM