2024/10/14

今天我写了一个生成随机四则运算题的程序。
完成了选择年级、选择题数等功能。
import javax.swing.;
import java.awt.
;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

class ArithmeticProblem {
protected int operandCount;
protected boolean hasMultiplication;
protected boolean hasDivision;
protected boolean hasParentheses;
protected int lowerLimit;
protected int upperLimit;

public ArithmeticProblem(int operandCount, boolean hasMultiplication, boolean hasDivision, boolean hasParentheses, int lowerLimit, int upperLimit) {
    this.operandCount = operandCount;
    this.hasMultiplication = hasMultiplication;
    this.hasDivision = hasDivision;
    this.hasParentheses = hasParentheses;
    this.lowerLimit = lowerLimit;
    this.upperLimit = upperLimit;
}

public String generateProblem() {
    return "";
}

}

class SecondGradeProblem extends ArithmeticProblem {
public SecondGradeProblem() {
super(2, true, true, false, 0, 100);
}

@Override
public String generateProblem() {
    Random random = new Random();
    int num1 = random.nextInt(upperLimit - lowerLimit + 1) + lowerLimit;
    int num2 = random.nextInt(upperLimit - lowerLimit + 1) + lowerLimit;
    int operator = random.nextInt(4);
    String operatorStr;
    int result;
    switch (operator) {
        case 0:
            operatorStr = "+";
            result = num1 + num2;
            break;
        case 1:
            operatorStr = "-";
            result = num1 - num2;
            break;
        case 2:
            if (num1 % num2 == 0) {
                operatorStr = "÷";
                result = num1 / num2;
            } else {
                return generateProblem();
            }
            break;
        default:
            if (num2!= 0 && num1 % num2 == 0) {
                operatorStr = "×";
                result = num1 * num2;
            } else {
                return generateProblem();
            }
            break;
    }
    return num1 + " " + operatorStr + " " + num2 + " = ";
}

}

class ThirdGradeProblem extends SecondGradeProblem {
public ThirdGradeProblem() {
super();
operandCount = 4;
lowerLimit = 0;
upperLimit = 1000;
}

@Override
public String generateProblem() {
    Random random = new Random();
    StringBuilder problemBuilder = new StringBuilder();
    int[] operands = new int[operandCount];
    String[] operators = new String[operandCount - 1];
    for (int i = 0; i < operandCount; i++) {
        operands[i] = random.nextInt(upperLimit - lowerLimit + 1) + lowerLimit;
    }
    for (int i = 0; i < operandCount - 1; i++) {
        int operator = random.nextInt(4);
        switch (operator) {
            case 0:
                operators[i] = "+";
                break;
            case 1:
                operators[i] = "-";
                break;
            case 2:
                if (operands[i + 1]!= 0 && operands[i] % operands[i + 1] == 0) {
                    operators[i] = "÷";
                } else {
                    return generateProblem();
                }
                break;
            default:
                if (operands[i + 1]!= 0 && operands[i] % operands[i + 1] == 0) {
                    operators[i] = "×";
                } else {
                    return generateProblem();
                }
                break;
        }
    }
    problemBuilder.append(operands[0]);
    for (int i = 0; i < operandCount - 1; i++) {
        problemBuilder.append(" ").append(operators[i]).append(" ").append(operands[i + 1]);
    }
    return problemBuilder.toString();
}

}

class FourthGradeProblem extends ThirdGradeProblem {
public FourthGradeProblem() {
super();
hasParentheses = true;
}

@Override
public String generateProblem() {
    Random random = new Random();
    StringBuilder problemBuilder = new StringBuilder();
    int operandCount = random.nextInt(2) + 3;
    int[] operands = new int[operandCount];
    String[] operators = new String[operandCount - 1];
    for (int i = 0; i < operandCount; i++) {
        operands[i] = random.nextInt(upperLimit - lowerLimit + 1) + lowerLimit;
    }
    for (int i = 0; i < operandCount - 1; i++) {
        int operator = random.nextInt(4);
        switch (operator) {
            case 0:
                operators[i] = "+";
                break;
            case 1:
                operators[i] = "-";
                break;
            case 2:
                if (operands[i + 1]!= 0 && operands[i] % operands[i + 1] == 0) {
                    operators[i] = "÷";
                } else {
                    return generateProblem();
                }
                break;
            default:
                if (operands[i + 1]!= 0 && operands[i] % operands[i + 1] == 0) {
                    operators[i] = "×";
                } else {
                    return generateProblem();
                }
                break;
        }
    }
    if (hasParentheses && random.nextBoolean()) {
        int start = random.nextInt(operandCount - 1);
        int end = start + random.nextInt(operandCount - start);
        problemBuilder.append("(");
        for (int i = start; i < end; i++) {
            problemBuilder.append(operands[i]).append(" ").append(operators[i]).append(" ");
        }
        problemBuilder.deleteCharAt(problemBuilder.length() - 1);
        problemBuilder.append(")");
    } else {
        problemBuilder.append(operands[0]);
        for (int i = 0; i < operandCount - 1; i++) {
            problemBuilder.append(" ").append(operators[i]).append(" ").append(operands[i + 1]);
        }
    }
    return problemBuilder.toString();
}

}

class MathQuiz {
private List problems;
private List wrongProblems;
private int wrongCount;

public MathQuiz() {
    problems = new ArrayList<>();
    wrongProblems = new ArrayList<>();
    wrongCount = 0;
}

public void generateProblems(int count, ArithmeticProblem problemGenerator) {
    for (int i = 0; i < count; i++) {
        problems.add(problemGenerator.generateProblem());
    }
}

public void checkAnswers(List<String> answers) {
    for (int i = 0; i < problems.size(); i++) {
        String problem = problems.get(i);
        String answer = answers.get(i);
        if (!evaluateAnswer(problem, answer)) {
            wrongProblems.add(problem);
            wrongCount++;
        }
    }
}

private boolean evaluateAnswer(String problem, String answer) {
    int result = calculateResult(problem);
    return Integer.parseInt(answer) == result;
}

private int calculateResult(String problem) {
    String[] parts = problem.split(" ");
    int result = Integer.parseInt(parts[0]);
    for (int i = 1; i < parts.length; i += 2) {
        String operator = parts[i];
        int operand = Integer.parseInt(parts[i + 1]);
        switch (operator) {
            case "+":
                result += operand;
                break;
            case "-":
                result -= operand;
                break;
            case "×":
                result *= operand;
                break;
            case "÷":
                result /= operand;
                break;
        }
    }
    return result;
}

public void redoWrongProblems() {
    problems = wrongProblems;
    wrongProblems = new ArrayList<>();
    wrongCount = 0;
}

public int getWrongCount() {
    return wrongCount;
}

}

class MathQuizGUI {
private JFrame frame;
private JComboBox gradeComboBox;
private JTextField problemCountField;
private JButton generateButton;
private JTextArea problemArea;
private JTextField answerField;
private JButton submitButton;
private JTextArea resultArea;
private JButton redoButton;

public MathQuizGUI() {
    frame = new JFrame("Math Quiz");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(new BorderLayout());

    // 设置整体界面风格为 Nimbus
    try {
        for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    JPanel inputPanel = new JPanel();
    inputPanel.setLayout(new FlowLayout());
    inputPanel.setBackground(new Color(230, 230, 230)); // 输入面板背景色

    gradeComboBox = new JComboBox<>(new String[]{"小学二年级", "小学三年级", "小学四年级"});
    gradeComboBox.setFont(new Font("宋体", Font.PLAIN, 14)); // 年级选择框字体
    inputPanel.add(gradeComboBox);

    problemCountField = new JTextField(5);
    problemCountField.setFont(new Font("宋体", Font.PLAIN, 14)); // 题目数量输入框字体
    inputPanel.add(new JLabel("题目数量:"));
    inputPanel.add(problemCountField);

    generateButton = new JButton("生成题目");
    generateButton.setFont(new Font("宋体", Font.PLAIN, 14)); // 生成题目按钮字体
    generateButton.setBackground(new Color(153, 204, 255)); // 按钮背景色
    generateButton.setForeground(Color.WHITE); // 按钮文字颜色
    inputPanel.add(generateButton);

    frame.add(inputPanel, BorderLayout.NORTH);

    problemArea = new JTextArea(10, 30);
    problemArea.setFont(new Font("宋体", Font.PLAIN, 14)); // 题目显示区域字体
    problemArea.setEditable(false);
    problemArea.setBackground(Color.WHITE); // 题目显示区域背景色
    JScrollPane problemScrollPane = new JScrollPane(problemArea);
    frame.add(problemScrollPane, BorderLayout.CENTER);

    answerField = new JTextField(10);
    answerField.setFont(new Font("宋体", Font.PLAIN, 14)); // 答案输入框字体
    submitButton = new JButton("提交答案");
    submitButton.setFont(new Font("宋体", Font.PLAIN, 14)); // 提交答案按钮字体
    submitButton.setBackground(new Color(102, 204, 102)); // 按钮背景色
    submitButton.setForeground(Color.WHITE); // 按钮文字颜色
    JPanel answerPanel = new JPanel();
    answerPanel.add(answerField);
    answerPanel.add(submitButton);
    frame.add(answerPanel, BorderLayout.SOUTH);

    resultArea = new JTextArea(5, 30);
    resultArea.setFont(new Font("宋体", Font.PLAIN, 14)); // 结果显示区域字体
    resultArea.setEditable(false);
    resultArea.setBackground(Color.WHITE); // 结果显示区域背景色
    JScrollPane resultScrollPane = new JScrollPane(resultArea);
    frame.add(resultScrollPane, BorderLayout.EAST);

    redoButton = new JButton("重练错题");
    redoButton.setFont(new Font("宋体", Font.PLAIN, 14)); // 重练错题按钮字体
    redoButton.setBackground(new Color(255, 153, 153)); // 按钮背景色
    redoButton.setForeground(Color.WHITE); // 按钮文字颜色
    frame.add(redoButton, BorderLayout.WEST);

    generateButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            generateProblems();
        }
    });

    submitButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            checkAnswers();
        }
    });

    redoButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            redoWrongProblems();
        }
    });
}

private void generateProblems() {
    int problemCount;
    try {
        problemCount = Integer.parseInt(problemCountField.getText());
    } catch (NumberFormatException ex) {
        resultArea.setText("请输入有效的题目数量。");
        return;
    }
    ArithmeticProblem problemGenerator;
    switch (gradeComboBox.getSelectedIndex()) {
        case 0:
            problemGenerator = new SecondGradeProblem();
            break;
        case 1:
            problemGenerator = new ThirdGradeProblem();
            break;
        default:
            problemGenerator = new FourthGradeProblem();
            break;
    }
    MathQuiz quiz = new MathQuiz();
    quiz.generateProblems(problemCount, problemGenerator);
    StringBuilder problemText = new StringBuilder();
    for (String problem : quiz.problems) {
        problemText.append(problem).append("\n");
    }
    problemArea.setText(problemText.toString());
}

private void checkAnswers() {
    String problemText = problemArea.getText();
    String[] problems = problemText.split("\n");
    String[] answers = new String[problems.length];
    for (int i = 0; i < problems.length; i++) {
        answers[i] = JOptionPane.showInputDialog(frame, problems[i]);
    }
    MathQuiz quiz = new MathQuiz();
    for (String problem : problems) {
        quiz.problems.add(problem);
    }
    quiz.checkAnswers(Arrays.asList(answers));
    int wrongCount = quiz.getWrongCount();
    StringBuilder resultText = new StringBuilder();
    for (int i = 0; i < problems.length; i++) {
        boolean isCorrect = quiz.evaluateAnswer(problems[i], answers[i]);
        resultText.append(problems[i]).append(" 你的答案:").append(answers[i]).append(" ").append(isCorrect? "正确" : "错误").append("\n");
    }
    resultText.append("\n错题数量:").append(wrongCount);
    resultArea.setText(resultText.toString());
}

private void redoWrongProblems() {
    MathQuiz quiz = new MathQuiz();
    StringBuilder problemText = new StringBuilder();
    for (String problem : problemArea.getText().split("\n")) {
        quiz.problems.add(problem);
        problemText.append(problem).append("\n");
    }
    quiz.redoWrongProblems();
    problemArea.setText(problemText.toString());
    resultArea.setText("重练错题。");
}

public void show() {
    frame.pack();
    frame.setVisible(true);
}

}
public class Main {
public static void main(String[] args) {
MathQuizGUI gui = new MathQuizGUI();
gui.show();
}
}

posted on 2024-10-14 23:25  不耻  阅读(3)  评论(0编辑  收藏  举报

导航