首页 > 其他分享 >2024/10/14

2024/10/14

时间:2024-10-14 23:22:15浏览次数:1  
标签:10 14 operands int 2024 new public append String

今天我写了一个生成随机四则运算题的程序。
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();
}
}

标签:10,14,operands,int,2024,new,public,append,String
From: https://www.cnblogs.com/buchi/p/18466440

相关文章

  • 2024今日最新漂亮的早安早上好精选图片,问候情谊好, 天天都美好
    清晨!轻轻地一声问候,融入了所有的心愿;淡淡的一句祝福,倾注了无限的真诚。人生是一道风景,快乐是一种心情。在忙碌交织的岁月里,我们永远珍惜这份友情!祝福吉祥安康!开心快乐每一天!幸福并不复杂。饿时,饭是幸福,够饱即可;渴时,水是幸福,够饮即可;穷时,钱是幸福,够用即可;累时,闲是幸福,够畅即可......
  • 2024年10月14日总结
    今日新学了20个单词,复习32个。上午上了一节数据结构课学了些栈和队列,下午上了java课。出于竞赛知识需要,晚上学了些二叉树三种遍历方式的相关知识。以下是我用cpp完成的前序,中序,后序遍历二叉树的代码实现。includestructTreeNode{intval;TreeNode*left;TreeNode*right;......
  • 10/14回文游戏
    includeusingnamespacestd;defineOK1;//定义宏观变量defineERROR0;defineOVERFLOW-2defineMASIZE100//定义栈的最大容量typedefstruct{char*base;char*top;intstacksize;}SqStack;intInitStack(SqStack&S)//初始化栈{S.base=newchar[MASIZE];......
  • 尚硅谷rabbitmq2024 工作模式路由篇 第11节 答疑
    StringexchangeName="test_direct";/!创建交换机人图全channel.exchangeDeclare(exchangeName,BuiltinExchangeType.DIREcT,b:true,b1:false,b2:false,map:null);/1创建队列Stringqueue1Name="test_direct_queue1";Stringqueue2Name="test......
  • 有缺陷的 Java 代码:Java 开发人员最常犯的 10 大错误
    Java是一种复杂的编程语言,很长一段时间以来一直主导着许多生态系统。可移植性、自动垃圾回收及其温和的学习曲线是使其成为软件开发的绝佳选择的一些因素。但是,与任何其他编程语言一样,它仍然容易受到开发人员错误的影响。本文探讨了Java开发人员最常犯的10大错误以......
  • 10.14日
    基本的匿名函数可以直接定义一个匿名函数,然后立即调用它。javascript(function(){console.log("这是一个匿名函数!");})();2.作为回调函数匿名函数非常常见于回调场景,比如数组的方法。javascriptconstnumbers=[1,2,3,4,5];constdoubled=numbers.map(functi......
  • 数学建模习题2.10
    fromscipy.integrateimportquadimportnumpyasnp第一部分:抛物线旋转体(修正后)defV1_quad(y):returnnp.pi*(4*y-y**2)V1_corrected,_=quad(V1_quad,1,3)第二部分保持不变V2=0.5*(4/3)*np.pi*23-(1/3)*np.pi*22*1计算总体积total_volume_co......
  • 2024.10 记录(1)
    \(2024\)年\(10\)月记录qwq。20240929联考T3考虑怎么快速判定一个图是否有四元环,可以度数小定向连到度数大的点,由三元环计数的分析方法,枚举\(i\)相邻的\(u\),定向连出的\(v\),判定\(i,v\)是否有向相邻,是\(O(m\sqrtm)\)的。考虑\(u\)的度数为\(d_u\),现在来分析一......
  • 24.10.09
    类只加载一次静态变量能否定义在构造方法中?不能注意:静态变量内的赋值是所有对象包括子类共享的是在方法区内的,而成员变量的赋值是是在堆内存是伴随着对象的,其他对象是不共享的。方法区加载类信息,在加载Person类信息的时候一起加载静态变量kongfu并附上了默认值。在栈内......
  • 24.10.08
    面向对象对象的创建及使用内存图方法区用于加载类信息,堆里面用于存放new出来的,栈中存放局部变量运行TestDemo2时首先加载TestDemo2类信息在加载Car类的信息,Car类new出来的对象存放在堆内存中,并对Car类中的成员变量附上默认值,new出来的对象有一个地址值0x123.在栈中声明Car......