Record a training

Record a training

Article directory

Title Analysis

subject

Write a command line "software" that can automatically generate four primary school calculation questions.

Specific requirements:

Any programming language can accept a digital input, and then output the corresponding number of four operation questions and answers. For example, if the input number is 30, then output 30 questions and answers. The expression must have at least two operators. The number is a positive integer within 100. The answer cannot be a negative number. Such as:
23 - 3 * 4 = 11

Extension requirements:

Look at the four calculation requirements of grade three, four and five in primary school, and gradually realize the difficulty of each grade. Write a blog to record your ideas for each extension. In the process of extension, do you develop the function of each grade's arithmetic problem independently, and there is no connection between the fourth grade's code and the third grade's code, or do you gradually put some common codes together? Or do you use an object-oriented approach, using base classes and subclasses to manage different requirements and implementation details?

Analysis

After a simple analysis, I assume that the difficulties of the third, fourth and fifth grades are as follows:
The third grade operation is less than 100. There are only four operations in which the answer can be a positive integer
 Fourth grade operation within 1000 integer answer can only be four operations with negative integer
 Four operations of decimal plus integer within 10000 in the third grade operation

Implementation ideas

  1. Generating topics
    • Generate numbers (based on grade difficulty)
    • Build operator
    • Concatenate numbers and operators
  2. Work out the answer.
    • Calculate the answer of the question according to the generated question
  3. Judge whether the answer meets the requirements
    • Judge whether the answer meets the requirements of difficulty (judge whether the major difficulty meets the requirements according to the grade difficulty)
  4. Output questions and answers

Expand the train of thought

According to the difficulty difference of grade 3, 4 and 5 assumed by me, there is only the difference between numbers and answers in grade 3, 4 and 5. Just pass in a parameter to distinguish grades in the code, generate numbers according to grades and judge whether it meets the difficulty requirements. The code for different grades is basically public code

Realization

Code

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Random;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

// The third grade operation is less than 100. There are only four operations in which the answer can be a positive integer
// Fourth grade operation within 1000 integer answer can only be four operations with negative integer
// Four operations of decimal plus integer within 10000 in the third grade operation
public class Main {

    static Random random = new Random();
    static Scanner sc = new Scanner(System.in);

    public static void main(String[] args) {
        System.out.println("Please enter grade:");
        int type = sc.nextInt();
        System.out.println("Please input the number of questions:");
        int count = sc.nextInt();
        for (int i = 0; i < count; i++) {
            System.out.println(getSubjectAndAnswer(type));
        }

    }

    /**
     * Get questions and answers
     * @param type grade
     * @return Return to questions and answers
     */
    private static String getSubjectAndAnswer(int type) {
        String subject = generateSubject(type);
        String answer = getAnswer(subject);
        if (type == 3) {
            //Answer cannot be greater than 1000 and answer cannot be negative or decimal
            if (answer.contains("-") || answer.contains(".") || Integer.parseInt(answer) > 1000) {
                while (answer.contains("-") || answer.contains(".") || Integer.parseInt(answer) > 1000) {
                    subject = generateSubject(type);
                    answer = getAnswer(subject);
                }
            }

        } else if (type == 4) {
            //Answer cannot be greater than 10000 or less than - 10000 and answer cannot be decimal
            if (answer.contains(".") || Integer.parseInt(answer) > 10000 || Integer.parseInt(answer) < -10000) {
                while (answer.contains(".") || Integer.parseInt(answer) > 10000 || Integer.parseInt(answer) < -10000) {
                    subject = generateSubject(type);
                    answer = getAnswer(subject);
                }
            }

        }
        return  subject + "=" + answer;
    }

    /**
     * Generate figures
     *
     * @param num Range of generated numbers
     * @return Return random numbers from 1 to 100
     */
    private static String generateNumbers(int num) {
        return String.valueOf(random.nextInt(num) + 1);
    }

    /**
     * Generating a decimal
     *
     * @return Return random numbers from 1 to 100
     */
    private static String generateDecimal() {
        return String.format("%.2f", random.nextDouble() * 100);
    }

    /**
     * Generate operation symbol
     *
     * @return Return operation symbol
     */
    private static String generateSymbol() {
        String[] symbols = {"+", "-", "x", "÷"};
        return symbols[random.nextInt(4)];
    }


    /**
     * Get numbers by grade
     *
     * @param type grade
     * @return Return number
     */
    public static String getNum(int type) {
        if (type == 3) {
            return generateNumbers(99);
        } else if (type == 4) {
            return generateNumbers(999);
        }
        return generateDecimal();

    }

    /**
     * Generating topics
     *
     * @param type grade
     * @return Return
     */
    private static String generateSubject(int type) {
        String subject = getNum(type);

        //Number of randomly obtained numbers
        int count = random.nextInt(2) + 2;
        String symbolFist = "";

        for (int i = 0; i < count; i++) {
            String symbol = generateSymbol();
            //Record first operator
            if (i == 0) {
                symbolFist = symbol;
            } else if (i == 1) {
                //Make sure that the first operator is different from the second
                while (symbolFist.equals(symbol)) {
                    symbol = generateSymbol();
                }
            }
            subject = subject + symbol + getNum(type);


        }
        return subject;
    }


    /**
     * Calculate the answer according to the question
     *
     * @param subject subject
     * @return Return
     */
    private static String getAnswer(String subject) {
        //Let's finish all the multiplication first
        while (subject.contains("x")) {
            subject = getResult(subject, "x");
        }
        //All division calculations completed
        while (subject.contains("÷")) {
            subject = getResult(subject, "÷");
        }
        //Let's finish all the multiplication first
        while (subject.contains("+")) {
            subject = getResult(subject, "+");
        }
        //Let's finish all the multiplication first
        while (subject.contains("-")) {
            //It is determined that the first number is negative and there is no minus sign after it
            if (subject.charAt(0) == '-' && subject.split("-").length < 3) {
                return subject;
            }
            subject = getResult(subject, "-");
        }
        return subject;
    }

    /**
     * Calculate results based on characters
     *
     * @param subject subject
     * @param symbol  Operation symbols to be calculated
     * @return Return the calculated string
     */
    private static String getResult(String subject, String symbol) {
        Pattern r = Pattern.compile("[0-9\\.]*" + symbol + "[0-9\\.]*");
        if ("+".equals(symbol)) {
            r = Pattern.compile("[0-9\\.]*\\+[0-9\\.]*");
        }
        Matcher m = r.matcher(subject);
        boolean isFind = m.find();
        if (!isFind) {
            return "";
        }
        String[] nums;
        if ("+".equals(symbol)) {
            nums = m.group(0).split("\\+");
        } else {
            nums = m.group(0).split(symbol);
            //Special judgment formula such as - 1-1
            if (m.group(0).charAt(0) == '-') {
                r = Pattern.compile("-[0-9\\.]*-[0-9\\.]*");
                m = r.matcher(subject);
                m.find();
                String[] nums_tmp = m.group(0).split(symbol);
                nums[0] = nums_tmp[1];
                nums[1] = nums_tmp[2];
            } else {
                nums = m.group(0).split(symbol);
            }
        }
        String result = "";

        switch (symbol) {
            case "+":
                //Determine whether there is decimal
                if (subject.contains(".")) {
                    BigDecimal a = new BigDecimal(nums[0]);
                    BigDecimal b = new BigDecimal(nums[1]);
                    result = String.valueOf(a.add(b));
                } else {
                    result = String.valueOf(Integer.parseInt(nums[0]) + Integer.parseInt(nums[1]));
                }
                break;
            case "-":
                if (subject.contains(".")) {
                    BigDecimal a = new BigDecimal(nums[0]);
                    BigDecimal b = new BigDecimal(nums[1]);
                    result = String.valueOf(a.subtract(b));
                } else {
                    result = String.valueOf(Integer.parseInt(nums[0]) - Integer.parseInt(nums[1]));
                }
                break;
            case "x":
                if (subject.contains(".")) {
                    BigDecimal a = new BigDecimal(nums[0]);
                    BigDecimal b = new BigDecimal(nums[1]);
                    result = String.valueOf(a.multiply(b));
                } else {
                    result = String.valueOf(Integer.parseInt(nums[0]) * Integer.parseInt(nums[1]));
                }
                break;
            case "÷":
                BigDecimal a = new BigDecimal(nums[0]);
                BigDecimal b = new BigDecimal(nums[1]);
                result = String.valueOf(a.divide(b, 4, RoundingMode.HALF_UP));
                break;
        }
        subject = subject.replace(m.group(0), result);
        return subject;
    }

}

Program output

Grade three

Please enter grade:
3
 Please enter the number of questions:
3
95+75-22=148
69+67-17=119
35x57-97x12=831

fourth grade

Please enter grade:
3
 Please enter the number of questions:
3
62x4-42=206
56+73x50=3706
22x31+13=695

fifth grade

Please enter grade:
5
 Please enter the number of questions:
3
87.30+45.18÷32.57=88.6872
37.58+47.73-29.61-67.21=-11.51
44.93x24.08-79.86=1002.0544
Published 5 original articles, won praise 29, visited 60000+
Private letter follow

Keywords: Java less Programming

Added by jwk811 on Mon, 09 Mar 2020 08:06:26 +0200