|
|
// ExamService.java
|
|
|
package com.example.myapp.service;
|
|
|
|
|
|
import com.example.myapp.model.Exam;
|
|
|
import com.example.myapp.model.Question;
|
|
|
import java.util.List;
|
|
|
import java.util.concurrent.ConcurrentHashMap;
|
|
|
import java.util.Map;
|
|
|
|
|
|
public class ExamService {
|
|
|
private Map<String, Exam> userExams = new ConcurrentHashMap<>();
|
|
|
private static final ExamService instance = new ExamService();
|
|
|
|
|
|
public static ExamService getInstance() {
|
|
|
return instance;
|
|
|
}
|
|
|
|
|
|
public boolean generateExam(String gradeLevel, int questionCount, String email) {
|
|
|
try {
|
|
|
List<Question> questions = MathQuestionGenerator.generateQuestions(gradeLevel, questionCount);
|
|
|
Exam exam = new Exam(gradeLevel, questionCount, questions);
|
|
|
userExams.put(email, exam);
|
|
|
return true;
|
|
|
} catch (Exception e) {
|
|
|
e.printStackTrace();
|
|
|
return false;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
public Exam getCurrentExam(String email) {
|
|
|
return userExams.get(email);
|
|
|
}
|
|
|
|
|
|
public boolean submitAnswer(String email, int questionIndex, String selectedAnswer) {
|
|
|
Exam exam = userExams.get(email);
|
|
|
if (exam != null && questionIndex >= 0 && questionIndex < exam.getQuestions().size()) {
|
|
|
exam.getQuestions().get(questionIndex).setUserAnswer(selectedAnswer);
|
|
|
return true;
|
|
|
}
|
|
|
return false;
|
|
|
}
|
|
|
|
|
|
// 在 ExamService.java 的 calculateScore 方法中修改答案比较逻辑
|
|
|
public int calculateScore(String email) {
|
|
|
Exam exam = userExams.get(email);
|
|
|
if (exam == null) return 0;
|
|
|
|
|
|
int correctCount = 0;
|
|
|
for (Question question : exam.getQuestions()) {
|
|
|
String userAnswer = question.getUserAnswer();
|
|
|
String correctAnswer = question.getCorrectAnswer();
|
|
|
|
|
|
// 使用容差比较答案(针对小数)
|
|
|
if (isAnswerCorrect(userAnswer, correctAnswer)) {
|
|
|
correctCount++;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
int score = (int) ((correctCount * 100.0) / exam.getQuestions().size());
|
|
|
exam.setScore(score);
|
|
|
return score;
|
|
|
}
|
|
|
|
|
|
// 新增答案比较方法,支持小数容差
|
|
|
private boolean isAnswerCorrect(String userAnswer, String correctAnswer) {
|
|
|
if (userAnswer == null || correctAnswer == null) {
|
|
|
return false;
|
|
|
}
|
|
|
|
|
|
try {
|
|
|
// 去除选项标签(如"A. ")
|
|
|
String cleanUserAnswer = userAnswer.replaceAll("^[A-D]\\.\\s*", "");
|
|
|
String cleanCorrectAnswer = correctAnswer.replaceAll("^[A-D]\\.\\s*", "");
|
|
|
|
|
|
// 尝试解析为数字进行比较
|
|
|
double userValue = Double.parseDouble(cleanUserAnswer);
|
|
|
double correctValue = Double.parseDouble(cleanCorrectAnswer);
|
|
|
|
|
|
// 使用容差比较
|
|
|
return Math.abs(userValue - correctValue) < 0.01;
|
|
|
} catch (NumberFormatException e) {
|
|
|
// 如果无法解析为数字,进行字符串比较
|
|
|
return userAnswer.trim().equals(correctAnswer.trim());
|
|
|
}
|
|
|
}
|
|
|
|
|
|
public void clearExam(String email) {
|
|
|
userExams.remove(email);
|
|
|
}
|
|
|
} |