用Java实现,生成100以内加法/减法的算式,批量产生习题并用文件存储,批改练习并存储
时间: 2023-11-27 18:03:06 浏览: 137
以下是Java实现的代码,生成100以内加法/减法的算式,批量产生习题并用文件存储,批改练习并存储的过程:
```java
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
public class MathExerciseGenerator {
private static final int NUM_EXERCISES = 10; // 需要生成的练习数量
private static final int MAX_NUM = 100; // 最大数值范围
public static void main(String[] args) {
// 生成练习并存储到文件
generateExercises();
System.out.println("练习已生成并存储到文件。");
// 批改练习并存储到文件
checkExercises();
System.out.println("批改结果已存储到文件。");
}
private static void generateExercises() {
File file = new File("exercises.txt");
Random random = new Random();
try (FileWriter writer = new FileWriter(file)) {
for (int i = 1; i <= NUM_EXERCISES; i++) {
int num1 = random.nextInt(MAX_NUM + 1);
int num2 = random.nextInt(MAX_NUM + 1);
int operation = random.nextInt(2); // 0表示加法,1表示减法
String operator = (operation == 0) ? "+" : "-";
int result = (operation == 0) ? (num1 + num2) : (num1 - num2);
String exercise = String.format("%d %s %d = ", num1, operator, num2);
writer.write(exercise);
writer.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static void checkExercises() {
File file = new File("exercises.txt");
File resultFile = new File("results.txt");
try (FileWriter writer = new FileWriter(resultFile)) {
// 读取练习文件
java.util.Scanner scanner = new java.util.Scanner(file);
int index = 1;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.print(line);
// 用户输入答案
int answer = new java.util.Scanner(System.in).nextInt();
// 检查答案是否正确
boolean correct = checkAnswer(line, answer);
String result = String.format("%d. %s %d\n", index, (correct ? "正确" : "错误"), answer);
writer.write(result);
writer.flush();
index++;
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static boolean checkAnswer(String exercise, int answer) {
String[] parts = exercise.split(" ");
int num1 = Integer.parseInt(parts[0]);
String operator = parts[1];
int num2 = Integer.parseInt(parts[2]);
int result = (operator.equals("+")) ? (num1 + num2) : (num1 - num2);
return (answer == result);
}
}
```
该程序生成10道加法或减法的练习,将练习存储到文件`exercises.txt`中。用户可以在控制台中输入每道练习的答案,程序会检查答案是否正确,并将批改结果存储到文件`results.txt`中。
阅读全文