下载
commons-csv-1.8.jar
网址:commons-csv-1.8.jar下载及Maven、Gradle引入代码,pom文件及包内class -时代Java (nowjava.com)
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class MathExercisesCSV {
public static void main(String[] args) {
// 生成算式和保存到CSV文件
generateAndSaveExercises("math_exercises.csv", 20);
// 从CSV文件加载算式并使用
List<Exercise> loadedExercises = loadExercisesFromCSV("math_exercises.csv");
for (Exercise exercise : loadedExercises) {
System.out.println(exercise.getExpression() + " = " + exercise.getAnswer());
}
}
// 生成并保存习题到CSV文件
public static void generateAndSaveExercises(String fileName, int numExercises) {
List<Exercise> exercises = new ArrayList<>();
Random random = new Random();
for (int i = 0; i < numExercises; i++) {
int num1 = random.nextInt(10) + 1;
int num2 = random.nextInt(10) + 1;
char operator = randomOperator();
String expression = num1 + " " + operator + " " + num2;
int answer = calculateExpression(num1, num2, operator);
exercises.add(new Exercise(expression, answer));
}
try (PrintWriter writer = new PrintWriter(new File(fileName))) {
writer.println("Expression,Answer");
for (Exercise exercise : exercises) {
writer.println(exercise.getExpression() + "," + exercise.getAnswer());
}
System.out.println("习题已生成并保存到 " + fileName + " 文件。");
} catch (IOException e) {
e.printStackTrace();
}
}
// 随机选择算术操作符
private static char randomOperator() {
char[] operators = {'+', '-', '*', '/'};
return operators[new Random().nextInt(operators.length)];
}
// 计算数学表达式的结果
private static int calculateExpression(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:
throw new IllegalArgumentException("无效的运算符");
}
}
// 加载习题数据从CSV文件
public static List<Exercise> loadExercisesFromCSV(String fileName) {
List<Exercise> exercises = new ArrayList<>();
String line;
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
// 读取标题行
reader.readLine();
while ((line = reader.readLine()) != null) {
String[] data = line.split(",");
if (data.length == 2) {
String expression = data[0];
int answer = Integer.parseInt(data[1]);
exercises.add(new Exercise(expression, answer));
}
}
} catch (IOException e) {
e.printStackTrace();
}
return exercises;
}
}
class Exercise {
private String expression;
private int answer;
public Exercise(String expression, int answer) {
this.expression = expression;
this.answer = answer;
}
public String getExpression() {
return expression;
}
public int getAnswer() {
return answer;
}
}