尝试将生成的算式及习题长期保存下来,建议采用CSV形式存储。提交实现效果截图及相关代码。


import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
import java.util.Scanner;
public class MathOperate_File{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入要生成题目数量:");
int numberOfQuestions = scanner.nextInt(); // 指定生成题目的数量
generateMathQuestions(numberOfQuestions);
}
public static void generateMathQuestions(int numQuestions) {
Random random = new Random();
try {
FileWriter writer = new FileWriter("math_questions.csv");
for (int i = 0; i < numQuestions; i++) {
int operand1 = random.nextInt(100); // 随机生成第一个操作数(0-99之间的整数)
int operand2 = random.nextInt(100); // 随机生成第二个操作数(0-99之间的整数)
int operator = random.nextInt(2); // 随机选择运算符:0代表加法,1代表减法
String operatorSymbol;
int answer;
if (operator == 0) {
operatorSymbol = "+";
answer = operand1 + operand2;
} else {
operatorSymbol = "-";
answer = operand1 - operand2;
}
String question = operand1 + " " + operatorSymbol + " " + operand2;
String csvLine = question + "," + answer; // 以CSV格式拼接问题和答案
writer.write(csvLine + "\n"); // 写入CSV文件
System.out.println(question);
}
writer.close(); // 关闭文件写入
} catch (IOException e) {
System.err.println("无法创建CSV文件或写入数据:" + e.getMessage());
}
}
}