批量产生习题并用文件存储,批改练习并存储,生成100以内加法/减法的算式
时间: 2024-01-11 18:03:58 浏览: 111
以下是使用Java批量产生习题并用文件存储,批改练习并存储,生成100以内加法/减法的算式的示例代码:
```java
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
public class MathExerciseGenerator {
private static final int MAX_NUMBER = 100;
private static final int NUM_EXERCISES = 10;
public static void main(String[] args) {
List<String> exercises = generateExercises(NUM_EXERCISES);
writeToFile(exercises, "exercises.txt");
System.out.println("请依次输入答案,每行一个答案:");
List<String> answers = readAnswers(NUM_EXERCISES);
writeToFile(answers, "answers.txt");
System.out.println("批改结果:");
checkAnswers(exercises, answers);
}
private static List<String> generateExercises(int num) {
List<String> exercises = new ArrayList<>();
Random random = new Random();
for (int i = 0; i < num; i++) {
int a = random.nextInt(MAX_NUMBER) + 1;
int b = random.nextInt(MAX_NUMBER) + 1;
boolean isAddition = random.nextBoolean();
int result = isAddition ? a + b : a - b;
String operator = isAddition ? "+" : "-";
exercises.add(a + " " + operator + " " + b + " = ");
}
return exercises;
}
private static void writeToFile(List<String> lines, String fileName) {
try (FileWriter writer = new FileWriter(new File(fileName))) {
for (String line : lines) {
writer.write(line + "\n");
}
System.out.println("已生成文件:" + fileName);
} catch (IOException e) {
e.printStackTrace();
}
}
private static List<String> readAnswers(int num) {
List<String> answers = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < num; i++) {
String answer = scanner.nextLine();
answers.add(answer);
}
return answers;
}
private static void checkAnswers(List<String> exercises, List<String> answers) {
int numCorrect = 0;
for (int i = 0; i < exercises.size(); i++) {
String exercise = exercises.get(i);
String answer = answers.get(i);
int expected = Integer.parseInt(exercise.replaceAll("= ", ""));
int actual = Integer.parseInt(answer);
if (actual == expected) {
numCorrect++;
System.out.println(exercise + answer + " 正确");
} else {
System.out.println(exercise + answer + " 错误");
}
}
System.out.println("总共答对 " + numCorrect + " 题,答错 " + (NUM_EXERCISES - numCorrect) + " 题。");
}
}
```
在上面的代码中,我们使用了generateExercises()方法来生成指定数量的算式,并将它们写入到一个文件中;使用readAnswers()方法从控制台读取用户输入的答案,并将它们写入到另一个文件中;使用checkAnswers()方法来批改用户的答案,并输出批改结果。
注意,我们在写文件时使用了try-with-resources语句来自动关闭文件流,以避免手动关闭文件流时出现的错误。此外,我们还使用了Scanner类来读取用户的输入。
阅读全文