关于PPT的课后作业

动手动脑问题应用的是方法重载。
课后作业代码:
import java.util.*;

public class ArithmeticExam {
private static final Random random = new Random();
private static final Scanner scanner = new Scanner(System.in);
private static final int TOTAL_QUESTIONS = 30;
private static final int TIME_LIMIT = 300; // 5分钟倒计时(秒)

private static Set<String> generatedQuestions = new HashSet<>();
private static List<QuestionResult> wrongAnswers = new ArrayList<>();

public static void main(String[] args) {
    System.out.println("=== 一位数四则运算考试 ===");
    System.out.println("考试规则:");
    System.out.println("- 共 " + TOTAL_QUESTIONS + " 道题");
    System.out.println("- 时间限制: " + TIME_LIMIT + " 秒");
    System.out.println("- 减法不允许出现负数");
    System.out.println("- 乘法结果不允许出现四位数");
    System.out.println("- 除法必须整除");
    System.out.println("=======================\n");
    
    System.out.print("按回车键开始考试...");
    scanner.nextLine();
    
    // 创建倒计时线程
    CountdownTimer timer = new CountdownTimer(TIME_LIMIT);
    Thread timerThread = new Thread(timer);
    timerThread.start();
    
    int correctCount = 0;
    boolean timeUp = false;
    
    // 开始考试
    for (int i = 1; i <= TOTAL_QUESTIONS; i++) {
        // 检查是否超时
        if (timer.isTimeUp()) {
            timeUp = true;
            System.out.println("\n⏰ 时间到!考试结束");
            break;
        }
        
        System.out.println("\n第 " + i + " 题 (剩余时间: " + timer.getRemainingTime() + "秒):");
        QuestionResult result = generateAndCheckQuestion(i);
        
        if (result.isCorrect()) {
            correctCount++;
        } else {
            wrongAnswers.add(result);
        }
    }
    
    // 停止计时器
    timer.stop();
    
    // 显示考试结果
    displayResults(correctCount, timeUp);
    
    // 显示错题
    if (!wrongAnswers.isEmpty()) {
        displayWrongAnswers();
    }
}

/**
 * 生成并检查一道题目
 */
private static QuestionResult generateAndCheckQuestion(int questionNumber) {
    String question;
    int correctAnswer;
    
    // 生成不重复的题目
    do {
        char operator = getRandomOperator();
        int num1, num2;
        
        do {
            num1 = random.nextInt(9) + 1; // 1-9
            num2 = random.nextInt(9) + 1; // 1-9
        } while (!isValidOperation(num1, num2, operator));
        
        correctAnswer = calculate(num1, num2, operator);
        question = num1 + " " + operator + " " + num2 + " = ";
        
    } while (generatedQuestions.contains(question));
    
    generatedQuestions.add(question);
    
    // 显示题目并获取答案
    System.out.print(question);
    long startTime = System.currentTimeMillis();
    String userInput = scanner.nextLine();
    long endTime = System.currentTimeMillis();
    
    // 处理用户输入
    int userAnswer;
    try {
        userAnswer = Integer.parseInt(userInput.trim());
    } catch (NumberFormatException e) {
        System.out.println("✗ 输入格式错误,视为答错");
        return new QuestionResult(questionNumber, question, correctAnswer, -1, false);
    }
    
    boolean isCorrect = (userAnswer == correctAnswer);
    
    if (isCorrect) {
        System.out.println("✓ 正确!");
    } else {
        System.out.println("✗ 错误!");
    }
    
    return new QuestionResult(questionNumber, question, correctAnswer, userAnswer, isCorrect);
}

/**
 * 获取随机运算符
 */
private static char getRandomOperator() {
    char[] operators = {'+', '-', '*', '/'};
    return operators[random.nextInt(operators.length)];
}

/**
 * 验证运算是否合法
 */
private static boolean isValidOperation(int num1, int num2, char operator) {
    switch (operator) {
        case '-':
            // 减法:不允许负数
            return num1 >= num2;
        case '*':
            // 乘法:结果不允许四位数(最大999)
            return num1 * num2 < 1000;
        case '/':
            // 除法:必须整除且除数不为0
            return num2 != 0 && num1 % num2 == 0;
        default:
            return true; // 加法总是合法的
    }
}

/**
 * 计算结果
 */
private static int calculate(int num1, int num2, char operator) {
    switch (operator) {
        case '+': return num1 + num2;
        case '-': return num1 - num2;
        case '*': return num1 * num2;
        case '/': return num1 / num2;
        default: return 0;
    }
}

/**
 * 显示考试结果
 */
private static void displayResults(int correctCount, boolean timeUp) {
    System.out.println("\n" + "=".repeat(50));
    System.out.println("考试结果统计");
    System.out.println("=".repeat(50));
    
    int answeredQuestions = timeUp ? (correctCount + wrongAnswers.size()) : TOTAL_QUESTIONS;
    double accuracy = (double) correctCount / answeredQuestions * 100;
    
    System.out.println("总题数: " + TOTAL_QUESTIONS);
    System.out.println("完成题数: " + answeredQuestions);
    System.out.println("正确题数: " + correctCount);
    System.out.println("错误题数: " + wrongAnswers.size());
    System.out.printf("正确率: %.2f%%\n", accuracy);
    
    if (timeUp) {
        System.out.println("未完成题数: " + (TOTAL_QUESTIONS - answeredQuestions));
    }
}

/**
 * 显示错题
 */
private static void displayWrongAnswers() {
    System.out.println("\n" + "=".repeat(50));
    System.out.println("错题回顾");
    System.out.println("=".repeat(50));
    
    for (QuestionResult wrong : wrongAnswers) {
        System.out.printf("第%d题: %s 你的答案: %d, 正确答案: %d\n",
                wrong.getQuestionNumber(),
                wrong.getQuestion(),
                wrong.getUserAnswer(),
                wrong.getCorrectAnswer());
    }
}

/**
 * 倒计时计时器
 */
static class CountdownTimer implements Runnable {
    private int remainingTime;
    private boolean timeUp = false;
    private boolean running = true;
    
    public CountdownTimer(int totalTime) {
        this.remainingTime = totalTime;
    }
    
    @Override
    public void run() {
        try {
            while (remainingTime > 0 && running) {
                Thread.sleep(1000);
                remainingTime--;
            }
            if (remainingTime <= 0) {
                timeUp = true;
                System.out.println("\n⏰ 时间到!");
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
    
    public boolean isTimeUp() {
        return timeUp;
    }
    
    public int getRemainingTime() {
        return remainingTime;
    }
    
    public void stop() {
        running = false;
    }
}

/**
 * 题目结果类
 */
static class QuestionResult {
    private int questionNumber;
    private String question;
    private int correctAnswer;
    private int userAnswer;
    private boolean correct;
    
    public QuestionResult(int questionNumber, String question, int correctAnswer, int userAnswer, boolean correct) {
        this.questionNumber = questionNumber;
        this.question = question;
        this.correctAnswer = correctAnswer;
        this.userAnswer = userAnswer;
        this.correct = correct;
    }
    
    // Getter方法
    public int getQuestionNumber() { return questionNumber; }
    public String getQuestion() { return question; }
    public int getCorrectAnswer() { return correctAnswer; }
    public int getUserAnswer() { return userAnswer; }
    public boolean isCorrect() { return correct; }
}

}
思路:使用Random生成1-9数字和随机运算符,通过Set去重确保题目不重复,用Scanner实时接收答案,TimerThread控制倒计时,最后统计正确率和显示错题。

总结:这是一个包含题目生成、输入验证、时间控制和结果统计的完整考试系统,通过面向对象设计确保代码结构清晰且功能完善。

posted @ 2025-10-08 13:32  Faster1990  阅读(6)  评论(0)    收藏  举报