以上代码中的"加法习题.txt"文件中只有算式没有答案,但是存在一下代码static List<String> readQuestionsFromFile(String filename) { List<String> questions = new ArrayList<>(); try (Scanner scanner = new Scanner(new File(filename))) { while (scanner.hasNextLine()) { String line = scanner.nextLine(); questions.add(line); } } catch (FileNotFoundException e) { System.out.println("File not found: " + filename); } return questions; } static int evaluateQuestion(String question) { String[] parts = question.split(" "); int a = Integer.parseInt(parts[0]); int b = Integer.parseInt(parts[2]); String operator = parts[1]; if (operator.equals("+")) { return a + b; } else { return a - b; } },怎样通过以上代码在if (index == 2) {}实现对于文件"答案.txt"的批改
时间: 2024-02-14 11:13:56 浏览: 65
在 if (index == 2) {} 中,可以调用 readQuestionsFromFile(String filename) 方法读取"加法习题.txt"文件中的算式列表,然后遍历每个算式,依次调用 evaluateQuestion(String question) 方法计算出答案,并将计算结果与"答案.txt"文件中的答案进行比较。如果计算结果与答案文件中的答案一致,则算式正确,否则算式错误。可以使用一个计数器来记录正确的算式数量,最终输出正确率。具体代码实现如下:
```java
static void checkAnswers(String questionsFile, String answersFile) {
List<String> questions = readQuestionsFromFile(questionsFile);
int total = questions.size();
int correct = 0;
try (Scanner scanner = new Scanner(new File(answersFile))) {
int i = 0;
while (scanner.hasNextLine() && i < total) {
String answer = scanner.nextLine();
String question = questions.get(i);
int result = evaluateQuestion(question);
if (result == Integer.parseInt(answer)) {
correct++;
}
i++;
}
} catch (FileNotFoundException e) {
System.out.println("File not found: " + answersFile);
return;
}
double accuracy = (double) correct / total * 100;
System.out.printf("Accuracy: %.2f%% (%d/%d)\n", accuracy, correct, total);
}
```
调用方式如下:
```java
checkAnswers("加法习题.txt", "答案.txt");
```
阅读全文