今日报告

今天完成了软件构造的作业,用类的封装完成加减乘除混合运算的题目列表

MathQuestion.Java
import java.util.Random;

// 题目类
public class MathQuestion {
    private String question;
    private String answer;

    public MathQuestion(int operand1, int operand2, int operator) {
        String operatorSymbol;
        int result;
        switch (operator) {
            case 0:
                operatorSymbol = "+";
                result = operand1 + operand2;
                break;
            case 1:
                operatorSymbol = "-";
                result = operand1 - operand2;
                break;
            case 2:
                operatorSymbol = "*";
                result = operand1 * operand2;
                break;
            case 3:
                operatorSymbol = "/";
                result = operand1 / operand2;
                break;
            default:
                throw new IllegalArgumentException("Invalid operator: " + operator);
        }

        question = operand1 + " " + operatorSymbol + " " + operand2 + " = ";
        answer = Integer.toString(result);
    }

    public String getQuestion() {
        return question;
    }

    public String getAnswer() {
        return answer;
    }
}
ExamPaper.Java
import java.util.Random;

// 试卷类
public class ExamPaper {
    private MathQuestion[] questions;

    public ExamPaper(int numberOfQuestions) {
        questions = generateQuestions(numberOfQuestions);
    }

    private MathQuestion[] generateQuestions(int numberOfQuestions) {
        MathQuestion[] questions = new MathQuestion[numberOfQuestions];
        Random random = new Random();
        for (int i = 0; i < numberOfQuestions; i++) {
            int operand1 = random.nextInt(100); // 第一个操作数,范围:0-99
            int operand2 = random.nextInt(100); // 第二个操作数,范围:0-99
            int operator = random.nextInt(4); // 运算符,0表示加法,1表示减法,2表示乘法,3表示除法

            questions[i] = new MathQuestion(operand1, operand2, operator);
        }
        return questions;
    }

    public void printPaper() {
        System.out.println("试卷:");
        for (int i = 0; i < questions.length; i++) {
            System.out.println("题目 " + (i + 1) + ": " + questions[i].getQuestion());
        }
    }

    public void printAnswers() {
        System.out.println("答案:");
        for (int i = 0; i < questions.length; i++) {
            System.out.println("题目 " + (i + 1) + ": " + questions[i].getQuestion() + " " + questions[i].getAnswer());
        }
    }
}
Main.Java
// 主函数类
public class Main {
    public static void main(String[] args) {
        int numberOfQuestions = 10;
        ExamPaper paper = new ExamPaper(numberOfQuestions);

        paper.printPaper();
        paper.printAnswers();
    }
}

 

posted @ 2023-10-18 19:25  周+⑦  阅读(22)  评论(0)    收藏  举报