Introduction to Software Engineering Personal Work 2

The teacher has upgraded the last assignment and added new features, so I will show my homework again.

Programming ideas: The last program design was just a simple two-digit operation. There is no need to filter the types of operators. This time I repackaged the last programming code and designed a new one. The method of inputting data, generating different expressions for different input data, and judging whether the formula generated by the program conforms to the standard. The formula that meets the requirements is stored in the string array, and then the expression in the array is output to the result.

Program source code:

  1 package Arithmetic; 
  2 
  3 import java.util.Scanner;
  4 
  5 public class yunsuan {
  6 
  7     
  8     public static void main(String[] args) {
  9         // TODO Auto-generated method stub
 10         String array1[]=new String[1000];
 11         input(array1);
 12 
 13     }
 14     public static void input(String array1[]){
 15         int a,b,c,d,e,f;
 16         Scanner scanner=new Scanner(System.in);
 17                  System.out.println("Please enter the number of generated questions (less than 1000 tracks):");
 18         a=scanner.nextInt();
 19                  System.out.println("Please enter a range of numbers (1-?):");
 20         b=scanner.nextInt();
 21                  System.out.println("Is there a multiplication and division method (including 1 for multiplication and division, and 0 for no inclusion)");
 22         c=scanner.nextInt();
 23                  System.out.println("Do you have parentheses (up to ten numbers can be supported, please enter 1 for parentheses, 0 if not included)");
 24         d=scanner.nextInt();
 25                  System.out.println("Addition or subtraction has negative numbers (please enter 1 for negative numbers, 0 for negative numbers)");
 26         e=scanner.nextInt();
 27                  System.out.println("There is no remainder in the division (please enter 1 for the remainder, 0 for the remainder)");
 28         f=scanner.nextInt();
 29         int m;
 30         boolean n,o,p;
 31         if(c==1)
 32             m=4;
 33         else m=2;
 34         if(d==1)
 35             n=true;
 36         else n=false;
 37         if(e==1)
 38             o=true;
 39         else o=false;
 40         if(f==1)
 41             p=true;
 42         else p=false;
 43         for(int i=0;i<a;i++){
 44             array1[i]=birth(b,m,n,o,p);
 45         }
 46         output(a,array1);
 47     }
 48 
 49     public static void output(int a,String []array1 ){
 50         for(int i=0;i<a;i++){
 51             System.out.println(array1[i]);
 52         }
 53     }
 54     public static String birth(int fanwei,int fuhao,boolean bra,boolean o,boolean p){
 55         int a=((int)(Math.random()*9))+2;
 56         int b,c;
 57         String str ="";
 58         for(int i=0;i<a;i++){
 59             b=(int)(Math.random()*fanwei)+1;
 60             c=(int)(Math.random()*fuhao);
 61             if(i==a-1)
 62                  str+=b+"=";
 63             else {
 64                 switch(c){
 65                 case 0: str+=b+"+";break;
 66                 case 1: str+=b+"-";break;
 67                 case 2: str+=b+"*";break;
 68                 case 3:    str+=b+"/";break;
 69                 }
 70                 
 71             }
 72             
 73         }
 74         if(bra&&((int)( Math.random()*100))>50){
 75             //Insert a pair of parentheses for express here
 76             
 77             int first = (int)(Math.random()*(a-1))+1;//The first number enclosed
 78             int next = (int)(Math.random()*(a-1))+1;//The last number enclosed
 79             if(first > next){//If the first number is greater than the second number, swap the values ​​of the two numbers
 80                 first = first^next;
 81                 next = first^next;
 82                 first=first^next;
 83             }
 84             if(next-first >= 2){//If the difference between next and first is less than 2, the following steps are not performed because there are at least two numbers in parentheses
 85                 //Length write down the length of the expression string, j write down the number of digits in the traversal string
 86                 int length = str.length(),j=0;
 87                 //Create a dynamic string with a string.
 88                 StringBuffer temp = new StringBuffer(str);
 89                 //Start looping through strings
 90                 for(int i=0; i < length; i++){
 91                     char cc = temp.charAt(i);//Remove the character subscripted as i
 92                     if(first==1&&i==0)        //If the first number enclosed in parentheses is the first operand in the expression, insert it at the beginning of the expression (
 93                         temp.insert(0, '(');
 94                     if(cc > '9' || cc < '0'){//If the current character is an operator character
 95                         j++;                //Said that just traversing a number, so j plus one
 96                         if(j==first-1){        //If j reaches the previous position of first, insert "(" after the current character.
 97                             temp.insert(i+1, '(');i++;
 98                         }
 99                         if(j==next)            //If j reaches the next position, insert a ") in front of the current character.
100                             temp.insert(i, ')');
101                     }
102                 }
103                 str = temp.toString();//Convert a dynamic string to a normal string
104             }
105         }
106         //Add or subtract with or without negative numbers
107         /*
108         if(!o){
109 
110             int length2 = str.length(),j=0,i;
111             int m=str.indexOf('-');
112             StringBuffer temp = new StringBuffer(str);
113             if(m>0){
114                 for( i=m-1; i>0; i--){
115                     char cc = temp.charAt(i);
116                     if(cc > '9' || cc < '0')
117                         break;
118                 }
119                 
120                 String hh=temp.substring(i+1, m-1);
121                 int x=Integer.valueOf(hh);
122                 
123                 for( i=m; i<length2; i++){
124                     char cc = temp.charAt(i);
125                     if(cc > '9' || cc < '0')
126                         break;
127                 }
128                 hh=temp.substring(m+1, i-1);
129                 int y=Integer.valueOf(hh);
130                 if(x-y<0){
131                     int v=x;
132                     x=y;
133                     y=v;
134                     }
135                     
136             }
137         
138         }
139                 / / There is no remainder of the division
140         if(!p){
141             int length2 = str.length(),j=0,i;
142             int m=str.indexOf('/');
143             StringBuffer temp = new StringBuffer(str);
144             if(m>0){
145                 for( i=m-1; i>0; i--){
146                     char cc = temp.charAt(i);
147                     if(cc > '9' || cc < '0')
148                         break;
149                 }
150                 String hh=temp.substring(i+1, m-1);
151                 int x=Integer.valueOf(hh);
152                 for( i=m; i<length2; i++){
153                     char cc = temp.charAt(i);
154                     if(cc > '9' || cc < '0')
155                         break;
156                 }
157                 hh=temp.substring(m+1, i-1);
158                 int y=Integer.valueOf(hh);
159                 if(x%y!=0)
160                     birth( fanwei, fuhao, bra,o, p);
161                     
162             }
163         }
164         */
165         //The judgment of the remainder is unusable due to the existence of parentheses.
166         
167         return str;
168     }
169 }

String expression evaluation:

  1 import java.util.Collections;
  2 import java.util.Stack;
  3 
  4 public class Calculator {
  5     private Stack<String> postfixStack  = new Stack<String>();//Suffix stack
  6     private Stack<Character> opStack  = new Stack<Character>();//Operator stack
  7     private int [] operatPriority  = new int[] {0,3,2,1,-1,1,0,2};//Operator precedence using the operator ASCII-40 to index
  8     public static void main(String[] args) {
  9         System.out.println(5+12*(3+5)/7.0);
 10         Calculator cal  = new Calculator();
 11         String s = "5+12*(3+5)/7";
 12         double result  = cal.calculate(s);
 13         System.out.println(result);
 14     }
 15 
 16     /**
 17           * Calculated according to the given expression
 18      * @param  Expression The expression to be evaluated, for example: 5+12*(3+5)/7
 19      * @return
 20      */
 21     public double calculate(String expression) {
 22         Stack<String> resultStack  = new Stack<String>();
 23         prepare(expression);
 24         Collections.reverse(postfixStack);//Reverse the suffix stack
 25         String firstValue  ,secondValue,currentValue;//The first value, the second value, and the arithmetic operator involved in the calculation
 26         while(!postfixStack.isEmpty()) {
 27             currentValue  = postfixStack.pop();
 28             if(!isOperator(currentValue.charAt(0))) {//If not an operator, it is stored in the operand stack
 29                 resultStack.push(currentValue);
 30             } else {//If it is an operator, take two values ​​from the operand stack and participate in the operation together with the value.
 31                  secondValue  = resultStack.pop();
 32                  firstValue  = resultStack.pop();
 33                  String tempResult  = calculate(firstValue, secondValue, currentValue.charAt(0));
 34                  resultStack.push(tempResult);
 35             }
 36         }
 37         return Double.valueOf(resultStack.pop());
 38     }
 39     
 40     /**
 41           * Data preparation stage converts expressions into suffix stacks
 42      * @param expression
 43      */
 44     private void prepare(String expression) {
 45         opStack.push(',');//The operator is placed in the bottom element comma, which has the lowest priority
 46         char[] arr  = expression.toCharArray();
 47         int currentIndex  = 0;//The position of the current character
 48         int count = 0;//The length of the last arithmetic operator to the length of the character of this arithmetic operator is convenient or between
 49         char currentOp  ,peekOp;//Current operator and top-of-stack operator
 50         for(int i=0;i<arr.length;i++) {
 51             currentOp = arr[i];
 52             if(isOperator(currentOp)) {//If the current character is an operator
 53                 if(count > 0) {
 54                     postfixStack.push(new String(arr,currentIndex,count));//Take the number between two operators
 55                 }
 56                 peekOp = opStack.peek();
 57                 if(currentOp == ')') {//Enclose the parentheses to remove the elements from the operator stack into the suffix stack until the left parenthesis is encountered
 58                     while(opStack.peek() != '(') {
 59                         postfixStack.push(String.valueOf(opStack.pop()));
 60                     }
 61                     opStack.pop();
 62                 } else {
 63                     while(currentOp != '(' && peekOp != ',' && compare(currentOp,peekOp) ) {
 64                         postfixStack.push(String.valueOf(opStack.pop()));
 65                         peekOp = opStack.peek();
 66                     }
 67                     opStack.push(currentOp);
 68                 }
 69                 count = 0;
 70                 currentIndex = i+1;
 71             } else {
 72                 count++;
 73             }
 74         }
 75         if(count > 1 || (count == 1 && !isOperator(arr[currentIndex]))) {//The last character is not a parenthesis or other operator is added to the suffix stack
 76             postfixStack.push(new String(arr,currentIndex,count));
 77         } 
 78         
 79         while(opStack.peek() != ',') {
 80             postfixStack.push(String.valueOf( opStack.pop()));//Add the remaining elements in the operator stack to the suffix stack
 81         }
 82     }
 83     
 84     /**
 85           * Determine if it is an arithmetic symbol
 86      * @param c
 87      * @return
 88      */
 89     private boolean isOperator(char c) {
 90         return c == '+' || c == '-' || c == '*' || c == '/' || c == '(' ||c == ')';
 91     }
 92     
 93     /**
 94           * Use ASCII code -40 to subscript to arithmetic symbol priority
 95      * @param cur
 96      * @param peek
 97      * @return
 98      */
 99     public  boolean compare(char cur,char peek) {//  If peek priority is higher than cur, return true, the default is peek priority is low
100         boolean result  = false;
101         if(operatPriority[(peek)-40] >= operatPriority[(cur) - 40]) {
102            result = true;
103         }
104         return result;
105     }
106     
107     /**
108           * Calculated according to the given arithmetic operator
109      * @param firstValue
110      * @param secondValue
111      * @param currentOp
112      * @return
113      */
114     private String calculate(String firstValue,String secondValue,char currentOp) {
115         String result  = "";
116         switch(currentOp) {
117             case '+':
118                 result = String.valueOf(ArithHelper.add(firstValue, secondValue));
119                 break;
120             case '-':
121                 result = String.valueOf(ArithHelper.sub(firstValue, secondValue));
122                 break;
123             case '*':
124                 result = String.valueOf(ArithHelper.mul(firstValue, secondValue));
125                 break;
126             case '/':
127                 result = String.valueOf(ArithHelper.div(firstValue, secondValue));
128                 break;
129         }
130         return result;
131     }
132 }

Screenshot of running results:

Week activity summary table

Time log

Defect record log

Reprinted at: https://www.cnblogs.com/wangfengbin/p/6532817.html

Intelligent Recommendation

Introduction to Software Engineering - Four Projects in Personal Projects

1. Task description 1.1 Overview A software that performs four arithmetic exercises of 3 to 5 operators independently, and the programming language is not limited. 1.2 Basic requirements The program c...

Introduction to Software Engineering (Part 2)

Note Reference: Software Engineering Teaching in Guangzhou University Software engineering is an important discipline in software engineering, and mastering software engineering principles is an impor...

Software Engineering Personal Project-Sudoku 2

Generate Sudoku Finals function...

Software Engineering Network 15 Personal Work 3 - Case Study

Software Engineering Personal Work 3 The first part: research, evaluation select" " APPCase study 1. Download and use to describe the simplest and most intuitive personal experience for the ...

The use of test tools in the project [the fifth personal work of software engineering practice]

[Software Engineering Comprehensive Practice] - use of test tools in the project [Jewish]SHOU 1759223 table of Contents: "Software Engineering Comprehensive Practice"···...

More Recommendation

Summary of software engineering personal work Word frequency program

First, use time I can only say that for a long time, the original programming skills are bad to die, but also to use c + + or cs, is simply terrible, so began to ask students grammar, structure, usage...

Software Engineering Learning Notes - First Week: Introduction to Software Engineering - 2

  Software survival cycle process     Classification of software survival cycle processes   Basic process (access, supply, development, operation, maintenance)     Suppor...

Introduction to Software Engineering Exercise 2 (1.2.3.5)

1. When developing a software, it is necessary to judge whether the original system model and the target are realistic. Whether the benefits brought by the system are large enough to be worth investin...

Software Engineering Introduction Exercise 2-4

The topic is as shown: Problem definition: Technical feasibility: Is there a little technology to monitor the physical condition of the patient and feedback to the doctor? Economic feasibility: The ec...

Software Engineering - Personal Summary

Promotion New software for learning and using mockplus: A simple and fast prototyping design tool. Suitable for software teams and individuals to use in the design phase of software development. Get s...

Copyright  DMCA © 2018-2026 - All Rights Reserved - www.programmersought.com  User Notice

Top