尝试将生成的算式及习题长期保存下来,建议采用CSV形式存储。提交实现效果及相关代码。
import java.io.FileWriter;标签:java,String,int,十月,List,十一日,questions,import From: https://www.cnblogs.com/binglinll/p/18509601
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class MathOperationGenerator {
public static void main(String[] args) {
int numberOfQuestions = 10; // 指定生成题目的数量
List<String> mathQuestions = generateMathQuestions(numberOfQuestions);
saveToCSV(mathQuestions, "math_questions.csv");
System.out.println("题目已保存到 math_questions.csv");
}
public static List<String> generateMathQuestions(int numQuestions) {
Random random = new Random();
List<String> questions = new ArrayList<>();
for (int i = 0; i < numQuestions; i++) {
int operand1 = random.nextInt(100);
int operand2 = random.nextInt(100);
int operator = random.nextInt(2);
String operatorSymbol;
int answer;
if (operator == 0) {
operatorSymbol = "+";
answer = operand1 + operand2;
} else {
operatorSymbol = "-";
answer = operand1 - operand2;
}
String question = operand1 + " " + operatorSymbol + " " + operand2 + " = ?";
questions.add(question);
}
return questions;
}
public static void saveToCSV(List<String> data, String fileName) {
try (FileWriter writer = new FileWriter(fileName)) {
for (String line : data) {
writer.write(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}