今日报告
今天完成了软件构造的第四次作业,主要是将生成的算术题保存到csv文件当中
ExamPaper.java
import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.util.Random; // 试卷类 public class ExamPaper { private MathQuestion[] questions; public ExamPaper(int numberOfQuestions) { questions = generateQuestions(numberOfQuestions); saveToCSV("equations.csv"); // 将问题和答案保存到CSV文件 } 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; } private void saveToCSV(String csvFileName) { try { // 创建一个BufferedWriter对象来写入CSV文件 BufferedWriter writer = new BufferedWriter(new FileWriter(csvFileName)); // 写入CSV文件的标题行 writer.write("Question Answer\n"); for (int i = 0; i < questions.length; i++) { // 将问题和答案写入CSV文件 writer.write(questions[i].getQuestion() + questions[i].getAnswer() + "\n"); } // 关闭文件写入流 writer.close(); System.out.println("CSV文件已成功创建:" + csvFileName); } catch (IOException e) { System.err.println("写入CSV文件时发生错误:" + e.getMessage()); } } 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(); } }
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; } }



浙公网安备 33010602011771号