20194589 automatically generates four arithmetic problem first edition report

demand analysis

Using the Java language to complete an automatically generated four arithmetic questions of procedure, a command-line software, select the type of questions need to be generated after the start, and then generate these questions in a loop.

feature design

  • basic skills
  1. 10 100 automatically generated within the two operands four operations, including addition, subtraction, calculation result is within 100
  2. Remove duplicate mode.
  3. You can control whether to generate the multiplication and division.
  4. Can control the digital range, the relevant parameters can be controlled.
  5. Number crunching can be negative.
  6. Generating operations subject to an external file stored result.txtin.
  • extensions
  1. Title generated after the next step, or may choose to re-generate the selection mode is generated.
  2. Generated task can have multiple values ​​involved in computing.
  3. Generated a negative result may contain.
  4. Examination results are displayed as division remainder in the form of, or decimal form.
  5. Select whether to output the title with the answer.

design

Only the client process to interact with a user, acquiring a random number, calculation data and so on are implemented by other classes

  1. MathFunctionSetting a model class that represents an equation, the equation contains the data also added to the calculated result of MathFunction resultin. Get the result function getResultfunction uses the decorator pattern to achieve.
  2. MathValueThis is a model class, to accomplish involved in computing a plurality of values, it is necessary to use treethe data model to represent the equation.
  3. RandomCreatorJust a class, single embodiment mode, by getRandomobtaining a random number method.
  4. Calculator Class computing interface, the equation used to calculate the results, because of the need to determine whether the final result, but also to show the calculated answer, computing class is essential.
  5. CalculatFactoryFactory class, according to the function provided by the client, select the Calculatorcalculated result.
  6. AddCalculatorInherited from the Calculatorrealization of addition.
  7. SubCalculatorInherited from the Calculatorrealization subtraction.
  8. MultiCalculatorInherited from the Calculatorrealization of multiplication.
  9. DivCalculatorInherited from the Calculatorrealization division.
  10. MathMasterFor managing the class key generating function. Equation 10 need to be calculated, then you need to use whileor forcyclic, content loop is also moved to this class, stored into this equation calculated field in the class mathFunctions. To form the corresponding equation by setting client, and the client by calling this function is printFunctionsprinted.
  11. MathElement MathFunctionAnd MathValueit is inherited from MathElementwith getValue function, by MathFunctionand MathValueimplement.

    Model-related class diagram


    Simple factory class diagram

Test Run

Ordinary run again

  • All the default options, the default function to achieve
  • Delete duplicate items
  • Output

Show extensions

  • Implement the extended capabilities of currently configured to generate different topic again
  • You can continue to choose to configure, or exit the function

Display parameters can be controlled function

  • You can control the number of questions
  • Type control subject, such as multiplication and division
  • Negative involved in computing

The results show produced negative

  • The result can be negative option

Paste the code

  1. MathFunction Get the results of the method

    public MathFunction(MathElement leftElement, int opeator, MathElement rightElement) {
        super();
        this.leftElement = leftElement;
        this.opeator = opeator;
        this.rightElement = rightElement;
        calculator = CalculatorFactory.getCalculator(opeator);
        op = calculator.getOpeator();
    }
    
    public int getOpeator() {
        return opeator;
    }
    
    @Override
    public int getValue() {
        return calculator.calc(leftElement.getValue(), rightElement.getValue());
    }
    
    public String getOutput(boolean result) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(leftElement.getValue() + " " + op + " " + rightElement.getValue());
        if (result) {
            stringBuilder.append(" = " + getValue());
        }
        return stringBuilder.toString();
    }
  2. CalculatorFactory The method of obtaining the corresponding class

    public static Calculator getCalculator(int op) {
        switch (op) {
        case 0:
            return new AddCalculator();
        case 1:
            return new SubCalculator();
        case 2:
            return new MultiCalculator();
        case 3:
            return new DivCalculator();
        default:
            throw new IllegalArgumentException("Unexpected value: " + op);
        }
    }
  3. RandomCreator Class, using the singleton

    public class RandomCreator {
        private static RandomCreator creator;
        private Random random;
        private RandomCreator() {
            random=new Random(System.currentTimeMillis());
        }
        public int getRandom(int range) {
            return random.nextInt(range+1);
        }
        public static RandomCreator getCreator() {
            if (creator == null) {
                creator=new RandomCreator();
            }
            return creator;
    
        }
    }
  4. MathMaster The main questions of obtaining the code

    /**
     * 获取试题
     */
    public void get() {
        mathFunctions.clear();
        for(int functionIndex=0;functionIndex<onceCreateCount;) {
    
            int left=RandomCreator.getCreator().getRandom(onceCreateValueRange);
            if (whetherHasNegativeNumber) {
                if (RandomCreator.getCreator().getRandom(1)==0) {//0 就添加负号
                    left=0-left;
                }
            }
            int right=RandomCreator.getCreator().getRandom(onceCreateValueRange);
            if (whetherHasNegativeNumber) {
                if (RandomCreator.getCreator().getRandom(1)==0) {//0 就添加负号
                    right=0-right;
                }
            }
            int op=getRandom();//根据当前是否含有乘除法获取不同的运算符
            MathFunction mathFunction=new MathFunction(new MathValue(left),op,new MathValue(right));
            int result=mathFunction.getValue();
            if (checkResult(result)) {//如果结果不符合,忽略这次结果
                mathFunctions.add(mathFunction);
                functionIndex++;
            }//忽略的结果不会增加
        }
    }
  5. Whether the client for controlling the current configuration according to regenerate

    String getInputString = scanner.next();
    char charAt = getInputString.charAt(0);
    MathMaster master = new MathMaster();
    while (!needExit(charAt)) {
        //···省略部分代码
        boolean exit=false;//退出下面的while 时是否还有退出整体的while
        while (true) {
            master.get();
            master.printFunctions(false);
                        FileWriter fileWriter=new FileWriter("result.txt");//打印到文件中
            fileWriter.write(master.getFuncString());
            fileWriter.flush();
            fileWriter.close();
            System.out.println("是否需要输出带有结果的题目,Y/e");
            getInputString = scanner.next();
            charAt = getInputString.charAt(0);
            if (needExit(charAt)) {
                exit=true;
                break;
            } else if (whetherCouldGoon(charAt)) {
                if (charAt == 'y' || charAt == 'Y') {
                    master.printFunctions(true);
                }
                System.out.println("重新开始,还是再生成一遍,Y/n/e");
                getInputString = scanner.next();
                charAt = getInputString.charAt(0);
                if (needExit(charAt)) {
                                        exit=true;
                    break;
                } else if (whetherCouldGoon(charAt)) {
                    if (charAt == 'y' || charAt == 'Y') {
                        //不做任何改变就可以在输出
                    }else {
                        break;//重新开始
                    }
                }
            } else {
                System.out.println(input_error);//重新开始
                break;
            }
        }
        if (exit) {
            break;
        }
            //···省略部分代码
    }
  6. AddCalculator Class code, and other similar computing

    public class AddCalculator implements Calculator {
    
        @Override
        public int calc(int left, int right) {
            return left+right;
        }
        /**
         * 从这里获取操作符,就不需要判断0 1 2 3 对应的+ - * (/) 了
         */
        @Override
        public char getOpeator() {
            return '+';
        }
    
    }

to sum up

  • Want to reach the most preferred is a modular function, the part of the operation into the function, easy operation and understanding of the program, the same operation can reuse code as code needExitand whetherCouldGoonthe same.
  • Further that class, to comply with the current class does not need to know "principle of least knowledge" or operating entity, then extract it to another class, then the appropriate action will be put into this category, one can reduce a class size, but also reduces the dependency between modules, when modifying part of the code, only need to modify the current class can, requiring no moving other classes, other classes is not necessary to recompile the participation process.
  • The use of design patterns. Use in this project of the "singleton" and "simple engineering model", using the Singleton pattern, MathMasteryou do not need management to generate random numbers. Use a simple factory pattern, so MathMasterjust need to get answers, without the need to manage what is currently performed operation, smooth decoupling.
  • Flexible use of the interface and superclass, to code reuse, polymorphism, which is the basis of design patterns.
  • Object-oriented thinking, all things are all objects.
  • The principle of a single object, each class only need to complete their operation is good, if a class uses a lot of class, it would have to consider whether or not these elements are put into the other class, and then call from here, rather than allow a class to do too much work.

PSP

PSP2.1 Scheduled Tasks Plan time (min) required to complete a total of The actual time required for completion (min)
Planning plan 10 5
Estimate It estimated that the task requires much time and planning generally work steps 10 10
Development Develop 95 253
Analysis Needs analysis (including learning new technologies) 10 8
Design Spec Generate design documents 10 10
Design Review Design review (and colleagues reviewed the design documents) 10 10
Coding Standard Code specifications (development of appropriate norms for the current development) 5 5
Design Specific design 10 20
Coding Specific coding 30 160
Code Review Code Review 10 10
Test Test (self-test, modify the code, submit code) 20 30
Reporting report 25 25
Test Report testing report 15 10
Size Measurement Computing workload 5 10
Postmortem & Process Improvement Plan Hindsight, and submission process improvement plan 5 5

Guess you like

Origin www.cnblogs.com/fuzhengyin/p/11519900.html