2024/9/30 日 日志

今天下午进行了国庆假期前的小测。
我们需要界面化生成30道四则运算题。在此次测试中,我原打算模仿迷宫游戏的格式将题目尽数输出。
但在简化过程多层循环时遇到了问题 i j的位置当然可变,但无法保证时在一行中输出不同的题目。加之频繁调整位置让过程变得复杂。
以下是滑轮完成。

Count.java的内容如下
点击查看代码
import java.util.ArrayList;
import java.util.Random;

class Count {
    ArrayList<Integer> number1 = new ArrayList<>();
    ArrayList<Integer> number2 = new ArrayList<>();
    ArrayList<Integer> number3 = new ArrayList<>();
    ArrayList<String> number4 = new ArrayList<>();

    public Count() {
        count();
    }

    private void count() {
        Random rand = new Random();
        String[] symbols = {"+", "-", "*", "/"};
        int count = 0;

        while (count < 30) {
            int num1 = rand.nextInt(100); // 生成0到99之间的随机数
            int num2 = rand.nextInt(1, 100); // 生成1到99之间的随机数,避免 num2 为 0

            int operationIndex = rand.nextInt(symbols.length);
            String operation = symbols[operationIndex];
            int result;

            // 依据运算符计算结果,并检查有效性
            switch (operation) {
                case "+":
                    result = num1 + num2;
                    break;
                case "-":
                    if (num1 < num2) continue; // 确保不出现负数
                    result = num1 - num2;
                    break;
                case "*":
                    if (num1 * num2 >= 1000) continue; // 确保乘法结果小于1000
                    result = num1 * num2;
                    break;
                case "/":
                    if (num1 % num2 != 0) continue; // 确保整除
                    result = num1/num2;
                    break;
                default:
                    continue; // 不应该到达这里
            }

            // 将有效的题目添加到相应的列表中
            number1.add(num1);
            number2.add(num2);
            number3.add(result);
            number4.add(operation);

            count++;
        }
    }

    public ArrayList<Integer> getNumber1() {
        return number1;
    }

    public ArrayList<Integer> getNumber2() {
        return number2;
    }

    public ArrayList<Integer> getNumber3() {
        return number3;
    }

    public ArrayList<String> getNumber4() {
        return number4;
    }
}

CountJFrame.java的内容如下

点击查看代码
import javax.swing.*;
import javax.swing.border.BevelBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class CountJFrame extends JFrame {
    Count count = new Count();
    JTextField[] inputFields;
    JLabel timerLabel;

    Timer timer;
    int remainingTime = 180; // 设置计时器为60 秒

    public CountJFrame() {
        // 界面初始化
        initJFrame();
        // 添加题目到界面
        initView();
        // 启动计时器
        startTimer();
        // 让界面显示
        this.setVisible(true);
    }

    private void initJFrame() {
        // 设置界面的宽高
        this.setSize(500, 400);
        // 设置标题
        this.setTitle("四则运算");
        // 设置界面置顶
        this.setAlwaysOnTop(true);
        // 设置界面居中
        this.setLocationRelativeTo(null);
        // 设置界面关闭
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        // 设置布局为 null
        this.setLayout(null);
    }

    // 添加题目
    private void initView() {
        int numQuestions = count.number1.size(); // 题目数量
        inputFields = new JTextField[numQuestions]; // 创建输入框数组

        // 设置计时器标签
        timerLabel = new JLabel("剩余时间: " + remainingTime + "秒");
        timerLabel.setBounds(10, 10, 200, 30);
        this.getContentPane().add(timerLabel);

        // 在 GridLayout 中显示题目
        JPanel questionPanel = new JPanel();
        questionPanel.setLayout(new GridLayout(0, 2, 10, 10)); // 每行2列
        for (int i = 0; i < numQuestions; i++) {
            // 创建题目标签
            JLabel questionLabel = new JLabel(count.number1.get(i) + " " + count.number4.get(i) +
                    " " + count.number2.get(i) + " = ?");
            questionLabel.setBorder(new BevelBorder(BevelBorder.LOWERED));
            questionPanel.add(questionLabel);

            // 创建输入框
            inputFields[i] = new JTextField(); // 修正这里
            questionPanel.add(inputFields[i]);
        }

        // 将题目面板添加到滚动面板中
        JScrollPane scrollPane = new JScrollPane(questionPanel);
        scrollPane.setBounds(10, 50, 460, 250); // 设置滚动面板的位置和大小
        this.getContentPane().add(scrollPane);

        // 添加提交按钮
        JButton submitButton = new JButton("提交");
        submitButton.setBounds(380, 310, 80, 30);
        submitButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                StringBuilder incorrectAnswers = new StringBuilder();
                boolean allCorrect = true;

                for (int i = 0; i < inputFields.length; i++) {
                    String userInput = inputFields[i].getText();
                    // 检查用户输入与正确答案是否相等
                    if (!userInput.equals(String.valueOf(count.number3.get(i)))) {
                        incorrectAnswers.append(count.number1.get(i))
                                .append(" ").append(count.number4.get(i))
                                .append(" ").append(count.number2.get(i))
                                .append(" = ? (正确答案: ")
                                .append(count.number3.get(i)).append(")\n");
                        allCorrect = false;
                    }
                }
                // 创建一个JDialog作为父窗口
                JDialog dialog = new JDialog(CountJFrame.this, "结果", true);
                dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
                dialog.setAlwaysOnTop(true);
                dialog.setLocationRelativeTo(CountJFrame.this); // 居中于主窗口

                if (allCorrect) {
                    JOptionPane.showMessageDialog(dialog, "所有答案正确!");
                } else {
                    JOptionPane.showMessageDialog(dialog, "有答案不正确,请查看:\n" + incorrectAnswers.toString());
                }
                timer.stop(); // 停止计时器
            }
        });
        this.getContentPane().add(submitButton);
    }

    // 启动计时器
    private void startTimer() {
        timer = new Timer(1000, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                remainingTime--;
                timerLabel.setText("剩余时间: " + remainingTime + "秒");
                if (remainingTime <= 0) {
                    timer.stop();
                    // 时间到时自动判断答案
                    JOptionPane.showMessageDialog(null, "时间到,请提交答案!");
                    StringBuilder incorrectAnswers = new StringBuilder();
                    boolean allCorrect = true;

                    for (int i = 0; i < inputFields.length; i++) {
                        String userInput = inputFields[i].getText();
                        // 检查用户输入与正确答案是否相等
                        if (!userInput.equals(String.valueOf(count.number3.get(i)))) {
                            incorrectAnswers.append(count.number1.get(i))
                                    .append(" ").append(count.number4.get(i))
                                    .append(" ").append(count.number2.get(i))
                                    .append(" = ? (正确答案: ")
                                    .append(count.number3.get(i)).append(")\n");
                            allCorrect = false;
                        }
                    }

                    if (allCorrect) {
                        JOptionPane.showMessageDialog(null, "所有答案正确!");
                    } else {
                        JOptionPane.showMessageDialog(null, "有答案不正确,请查看:\n" + incorrectAnswers.toString());
                    }
                }
            }
        });
        timer.start();
    }

    public static void main(String[] args) {
        new CountJFrame();
    }
}

Main.java的内容如下

点击查看代码
//20234023 张一衡
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        //界面
        new CountJFrame();


    }


}

当然,可做的优化还有很多,我将在后续完成。
在这里,我学到了一个新的用法即:
// 将题目面板添加到滚动面板中
JScrollPane scrollPane = new JScrollPane(questionPanel);
scrollPane.setBounds(10, 50, 460, 250); // 设置滚动面板的位置和大小
this.getContentPane().add(scrollPane);

以及网格结构
JPanel questionPanel = new JPanel();
questionPanel.setLayout(new GridLayout(0, 2, 10, 10)); // 每行2列

这样的使用避免了频繁的JLabel以及 JTextField的位置修改.

posted @   Moonbeamsc  阅读(8)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署
返回顶端
点击右上角即可分享
微信分享提示