首页 > 其他分享 >10 月20日

10 月20日

时间:2024-10-20 22:48:20浏览次数:6  
标签:10 20 int frame problems private new append

周一Java课上留的课后习题代码:
import javax.swing.;
import java.awt.
;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

abstract class ProblemGenerator {
protected int maxOperands;
protected int numberRange;
protected boolean allowMultiplicationAndDivision;
protected boolean includeParentheses;
protected Random random;

public ProblemGenerator(int maxOperands, int numberRange, boolean allowMultiplicationAndDivision, boolean includeParentheses) {
    this.maxOperands = maxOperands;
    this.numberRange = numberRange;
    this.allowMultiplicationAndDivision = allowMultiplicationAndDivision;
    this.includeParentheses = includeParentheses;
    this.random = new Random();
}

public abstract String generateProblem();

protected double getRandomNumber() {
    return random.nextInt(numberRange) + 1;
}

protected char getRandomOperation() {
    char[] operations = {'+', '-', '*', '/'};
    char op = operations[random.nextInt(operations.length)];
    if (!allowMultiplicationAndDivision && (op == '*' || op == '/')) {
        return '+';
    }
    return op;
}

}

class SecondGradeProblemGenerator extends ProblemGenerator {
public SecondGradeProblemGenerator() {
super(2, 100, true, false);
}

@Override
public String generateProblem() {
    int num1 = (int) getRandomNumber();
    int num2 = (int) getRandomNumber();
    char operation = getRandomOperation();
    if (operation == '/') {
        while (num2 == 0 || num1 % num2 != 0) {
            num1 = (int) getRandomNumber();
            num2 = (int) getRandomNumber();
        }
    }
    return String.format("%d %c %d", num1, operation, num2);
}

}

class ThirdGradeProblemGenerator extends SecondGradeProblemGenerator {
public ThirdGradeProblemGenerator() {
super();
this.maxOperands = 4;
this.numberRange = 1000;
}

@Override
public String generateProblem() {
    StringBuilder problem = new StringBuilder();
    int operands = random.nextInt(maxOperands - 1) + 2;
    for (int i = 0; i < operands; i++) {
        problem.append((int) getRandomNumber());
        if (i < operands - 1) {
            problem.append(" ").append(getRandomOperation()).append(" ");
        }
    }
    return problem.toString();
}

}

class FourthGradeProblemGenerator extends ThirdGradeProblemGenerator {
public FourthGradeProblemGenerator() {
super();
this.maxOperands = 5;
this.includeParentheses = true;
}

@Override
public String generateProblem() {
    StringBuilder problem = new StringBuilder();
    int operands = random.nextInt(maxOperands - 1) + 2;
    for (int i = 0; i < operands; i++) {
        if (includeParentheses && random.nextBoolean()) {
            problem.append("(");
        }
        problem.append((int) getRandomNumber());
        if (includeParentheses && random.nextBoolean()) {
            problem.append(")");
        }
        if (i < operands - 1) {
            problem.append(" ").append(getRandomOperation()).append(" ");
        }
    }
    return problem.toString();
}

}

public class MathQuizAppGUI {
private JFrame frame;
private JTextArea questionArea;
private JTextField answerField;
private JTextArea resultArea;
private JComboBox gradeSelector;
private ProblemGenerator problemGenerator;
private List mistakes = new ArrayList<>();
private List problems = new ArrayList<>();
private int correctCount = 0;
private int totalCount = 0;

public MathQuizAppGUI() {
    initComponents();
}

private void initComponents() {
    frame = new JFrame("Math Quiz");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(800, 600);
    frame.setLayout(new BorderLayout());

    JPanel topPanel = new JPanel();
    topPanel.setLayout(new GridLayout(2, 1));
    JLabel titleLabel = new JLabel("Math Quiz", JLabel.CENTER);
    titleLabel.setFont(new Font("Arial", Font.BOLD, 32));
    topPanel.add(titleLabel);

    String[] grades = {"Select Grade", "Second Grade", "Third Grade", "Fourth Grade"};
    gradeSelector = new JComboBox<>(grades);
    gradeSelector.setFont(new Font("Arial", Font.PLAIN, 24));
    gradeSelector.addActionListener(e -> gradeChanged());
    topPanel.add(gradeSelector);

    frame.add(topPanel, BorderLayout.NORTH);

    questionArea = new JTextArea(10, 20);
    questionArea.setEditable(false);
    questionArea.setFont(new Font("Arial", Font.PLAIN, 24));
    frame.add(new JScrollPane(questionArea), BorderLayout.CENTER);

    answerField = new JTextField();
    answerField.setFont(new Font("Arial", Font.PLAIN, 24));
    frame.add(answerField, BorderLayout.SOUTH);

    JPanel buttonPanel = new JPanel();
    JButton submitButton = new JButton("Submit Answer");
    submitButton.setFont(new Font("Arial", Font.PLAIN, 18));
    submitButton.addActionListener(new SubmitActionListener());
    buttonPanel.add(submitButton);

    JButton nextProblemButton = new JButton("Next Problem Set");
    nextProblemButton.setFont(new Font("Arial", Font.PLAIN, 18));
    nextProblemButton.addActionListener(e -> generateNewProblemSet(10));
    buttonPanel.add(nextProblemButton);

    frame.add(buttonPanel, BorderLayout.EAST);

    resultArea = new JTextArea(10, 20);
    resultArea.setEditable(false);
    frame.add(new JScrollPane(resultArea), BorderLayout.WEST);

    frame.setVisible(true);
}

private void gradeChanged() {
    String selectedGrade = (String) gradeSelector.getSelectedItem();
    switch (selectedGrade) {
        case "Second Grade":
            problemGenerator = new SecondGradeProblemGenerator();
            break;
        case "Third Grade":
            problemGenerator = new ThirdGradeProblemGenerator();
            break;
        case "Fourth Grade":
            problemGenerator = new FourthGradeProblemGenerator();
            break;
        default:
            problemGenerator = null;
            return;
    }
    generateNewProblemSet(10);
}

private void generateNewProblemSet(int count) {
    if (problemGenerator == null) {
        JOptionPane.showMessageDialog(frame, "Please select a grade level first.", "Error", JOptionPane.ERROR_MESSAGE);
        return;
    }

    problems.clear();
    for (int i = 0; i < count; i++) {
        problems.add(problemGenerator.generateProblem());
    }
    displayProblems();
}

private void displayProblems() {
    StringBuilder displayText = new StringBuilder();
    for (int i = 0; i < problems.size(); i++) {
        displayText.append((i + 1)).append(". ").append(problems.get(i)).append("\n");
        if ((i + 1) % 3 == 0) {
            displayText.append("\n");
        }
    }
    questionArea.setText(displayText.toString());
}

private class SubmitActionListener implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        String userAnswers = answerField.getText();
        String[] answers = userAnswers.split("\\s+");
        if (answers.length != problems.size()) {
            JOptionPane.showMessageDialog(frame, "Please answer all questions!", "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }

        resultArea.setText("");
        correctCount = 0;
        totalCount = problems.size();
        StringBuilder results = new StringBuilder();

        for (int i = 0; i < problems.size(); i++) {
            double correctAnswer = evaluateExpression(problems.get(i));
            try {
                double userAnswer = Double.parseDouble(answers[i]);
                if (Math.abs(userAnswer - correctAnswer) < 1e-9) {
                    correctCount++;
                    results.append("Correct: ").append(problems.get(i)).append(" = ").append(userAnswer).append("\n");
                } else {
                    mistakes.add(problems.get(i));
                    results.append("Wrong: ").append(problems.get(i)).append(" = ").append(correctAnswer).append("\n");
                }
            } catch (NumberFormatException ex) {
                mistakes.add(problems.get(i));
                results.append("Invalid input for ").append(problems.get(i)).append("\n");
            }
        }

        resultArea.setText(results.toString());
        double accuracy = ((double) correctCount / totalCount) * 100;
        JOptionPane.showMessageDialog(frame, "You got " + correctCount + " out of " + totalCount + " correct!\nAccuracy: " + accuracy + "%", "Results", JOptionPane.INFORMATION_MESSAGE);

        saveProblemsToFile();
    }
}

private void saveProblemsToFile() {
    try (BufferedWriter writer = new BufferedWriter(new FileWriter("problems.txt"))) {
        for (String problem : problems) {
            writer.write(problem + "\n");
        }
        JOptionPane.showMessageDialog(frame, "Problems saved to problems.txt", "Saved", JOptionPane.INFORMATION_MESSAGE);
    } catch (IOException e) {
        e.printStackTrace();
        JOptionPane.showMessageDialog(frame, "Failed to save problems", "Error", JOptionPane.ERROR_MESSAGE);
    }
}

private double evaluateExpression(String expr) {
    String[] tokens = expr.split(" ");
    double result = Double.parseDouble(tokens[0]);
    int index = 1;
    while (index < tokens.length) {
        String operator = tokens[index++];
        double nextNum = Double.parseDouble(tokens[index++]);
        switch (operator) {
            case "+":
                result += nextNum;
                break;
            case "-":
                result -= nextNum;
                break;
            case "*":
                result *= nextNum;
                break;
            case "/":
                result /= nextNum;
                break;
        }
    }
    return result;
}

public static void main(String[] args) {
    SwingUtilities.invokeLater(MathQuizAppGUI::new);
}

}

标签:10,20,int,frame,problems,private,new,append
From: https://www.cnblogs.com/yjx0903/p/18488107

相关文章

  • 2024-10-19:用go语言,给定一个正整数 k 和初始数组 nums = [1], 可以执行两种操作:将数组
    2024-10-19:用go语言,给定一个正整数k和初始数组nums=[1],可以执行两种操作:将数组中任一元素加一,或复制数组中任意元素并将其附加到数组末尾。求使得数组元素之和大于或等于k所需的最少操作次数。输入:k=11。输出:5。解释:可以对数组nums=[1]执行以下操作:将元......
  • 2024 CCPC 哈尔滨游记
    哈哈哈,铁牌选手仍然很开心。就是有点累,下一场济南和期中考试冲了,为了补考写了十封甚至九封邮件。从广州到哈尔滨就是从短袖短裤到羽绒服啊啊啊,真天南地北。哈尔滨真冷,风还大,然后感觉整个城市确实有衰落迹象,看到某些部分感觉回到了10年前。举办高校是东北林业大学,秋天有红的绿......
  • 2024/10/20: TypeScript 学习笔记三:TypeScript 类型系统
    一、TypeScript提供的对应类型:booleanstringnumberbigintundefinednullsymbol 二、object类型仅能够赋值给以下三种类型:顶端类型any和unknownObject类型空对象类型字面量“{}”注:所有类型都是顶端类型的子类型,所以object能够赋值给顶端类型any和unkno......
  • JSP & EL表达式 & JSTL -2024/10/20
    JSPJSP(全称:JavaServerPages):Java服务端页面。是一种动态的网页技术,其中既可以定义HTML、JS、CSS等静态内容,还可以定义Java代码的动态内容,也就是JSP=HTML+Java。导入JSP依赖<dependency><groupId>javax.servlet.jsp</groupId><artifactId>jsp-api</artifactI......
  • 基于django+vue+Vue基于新生入学报道管理系统3gd10【开题报告+程序+论文】-计算机毕设
    本系统(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。系统程序文件列表开题报告内容一、选题背景关于新生入学报道管理系统的研究,现有研究多集中在整体的学校管理系统层面,专门针对新生入学报道这一特殊阶段管理系统的研究较少。在国......
  • 活着就好20241020
    明天的2024年10月20日,第42周,农历甲辰[龙]年九月十九,周日 ......
  • 2024-2025 20241318 《计算机基础与程序设计》第四周学习总结
    这个作业属于哪个课程https://edu.cnblogs.com/campus/besti/2024-2025-1-CFAP这个作业要求在哪里https://www.cnblogs.com/rocedu/p/9577842.html#WEEK04这个作业的目标自学教材计算机科学概论(第七版)第4章,第5章并完成云班课测试《C语言程序设计》第3章并完成......
  • 2024-2025-1 20241419《计算机基础与程序设计》第四周学习总结
    作业信息课程要求目标:门电路组合电路,逻辑电路冯诺依曼结构CPU,内存,IO管理嵌入式系统,并行结构物理安全作业正文教程学习内容总结:数字电路:门电路:实现逻辑运算的单元电路,包括与、或、非等。组合电路:输出仅与当前输入有关的数字电路。逻辑电路:由逻辑门组成,输入输出信号......
  • 20222411 2024-2025-1 《网络与系统攻防技术》实验三实验报告
    1.实验内容1.1实践内容(1)正确使用msf编码器,veil-evasion,自己利用shellcode编程等免杀工具或技巧正确使用msf编码器,使用msfvenom生成如jar之类的其他文件veil,加壳工具使用C+shellcode编程(2)通过组合应用各种技术实现恶意代码免杀如果成功实现了免杀的,简单语言描述原理,不要......
  • 10.20
    修改了四则运算中的部分错误Grade3QuestionGenerator类点击查看代码packageqixun;importjava.util.Random;publicclassGrade3QuestionGeneratorextendsGrade2QuestionGenerator{publicGrade3QuestionGenerator(){this.operandCount=4;//操作数......