10.23

package 测试;
import java.util.*;
import javax.swing.JOptionPane;
public class a {
static final Random R = new Random();

public static void main(String[] args) {
    int wrong = 0;
    StringBuilder resultMessage = new StringBuilder();
    for (int i = 1; i <= 30; i++) {
        String exp = generateExpression();
        double std = calculate(exp);
        String userInput = JOptionPane.showInputDialog(null, 
                i + ". " + exp, 
                "数学测验 - 第" + i + "题", 
                JOptionPane.QUESTION_MESSAGE);
        if (userInput == null) {
            JOptionPane.showMessageDialog(null, "测验已取消", "提示", JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        double userAnswer;
        try {
            userAnswer = Double.parseDouble(userInput);
        } catch (NumberFormatException e) {
            userAnswer = Double.NaN;
        }
        
        String feedback;
        if (Math.abs(userAnswer - std) < 1e-6) {
            feedback = "正确";
        } else {
            feedback = "错误,正确答案:" + (std % 1 == 0 ? (long)std : std);
            wrong++;
        }
        
        resultMessage.append(i).append(". ").append(exp).append(userInput).append(" → ").append(feedback).append("\n");
        JOptionPane.showMessageDialog(null, feedback, "结果", JOptionPane.INFORMATION_MESSAGE);
    }
    double accuracy = (30 - wrong) * 100.0 / 30;
    resultMessage.append("\n------------------\n")
                .append(String.format("错题数:%d / 30,正确率:%.2f%%", wrong, accuracy));
    
    JOptionPane.showMessageDialog(null, resultMessage.toString(), "测验结果", JOptionPane.INFORMATION_MESSAGE);
}
private static String generateExpression() {
    int a = 0, b = 0, opType;
    
    while (true) {
        opType = R.nextInt(4);
        switch (opType) {
            case 0:
                a = 1 + R.nextInt(100);
                b = 1 + R.nextInt(100);
                break;
            case 1: 
                a = 1 + R.nextInt(100);
                b = 1 + R.nextInt(a);
                break;
            case 2: 
                a = 1 + R.nextInt(31);
                b = 1 + R.nextInt(31);
                if (a * b > 999) continue;
                break;
            case 3:
                b = 1 + R.nextInt(100);
                int q = 1 + R.nextInt(100 / b + 1);
                a = q * b;
                break;
        }
        break;
    }
    char operator = "+-*/".charAt(opType);
    return "" + a + operator + b + "=";
}
private static double calculate(String exp) {
    String[] parts = exp.split("[-+*/=]");
    int a = Integer.parseInt(parts[0]);
    int b = Integer.parseInt(parts[1]);
    char op = exp.replaceAll("[0-9]|=", "").charAt(0);
    
    switch (op) {
        case '+': return a + b;
        case '-': return a - b;
        case '*': return a * b;
        case '/': return (double) a / b;
        default:  return 0;
    }
}

}

posted @ 2025-10-29 22:55  muyuxiaxing  阅读(3)  评论(0)    收藏  举报