完善后台逻辑 #6

Merged
hnu202326010207 merged 2 commits from yinhaoming_branch into develop 5 months ago

@ -33,6 +33,13 @@
<version>${javafx.version}</version>
</dependency>
<!-- Jakarta Mail for SMTP -->
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>jakarta.mail</artifactId>
<version>2.0.1</version>
</dependency>
<!-- Testing Dependencies -->
<dependency>
<groupId>org.junit.jupiter</groupId>
@ -140,4 +147,4 @@
</plugin>
</plugins>
</build>
</project>
</project>

@ -1,140 +0,0 @@
package com.personalproject.auth;
import com.personalproject.model.DifficultyLevel;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
/**
* .
*/
public final class AccountRepository {
private final Map<String, UserAccount> accounts = new HashMap<>();
private final Map<String, String> registrationCodes = new HashMap<>();
/**
* .
*
* @param username .
* @param password .
* @return .
*/
public Optional<UserAccount> authenticate(String username, String password) {
if (username == null || password == null) {
return Optional.empty();
}
UserAccount account = accounts.get(username.trim());
if (account == null || !account.isRegistered()) {
return Optional.empty();
}
if (!account.password().equals(password.trim())) {
return Optional.empty();
}
return Optional.of(account);
}
/**
* Registers a new user account with email.
*
* @param username The username
* @param email The email address
* @param difficultyLevel The selected difficulty level
* @return true if registration was successful, false if username already exists
*/
public boolean registerUser(String username, String email, DifficultyLevel difficultyLevel) {
String trimmedUsername = username.trim();
String trimmedEmail = email.trim();
if (accounts.containsKey(trimmedUsername)) {
return false; // Username already exists
}
// Check if email is already used by another account
for (UserAccount account : accounts.values()) {
if (account.email().equals(trimmedEmail) && account.isRegistered()) {
return false; // Email already registered
}
}
UserAccount newAccount = new UserAccount(
trimmedUsername,
trimmedEmail,
"", // Empty password initially
difficultyLevel,
LocalDateTime.now(),
false); // Not registered until password is set
accounts.put(trimmedUsername, newAccount);
return true;
}
/**
* Sets the password for a user after registration.
*
* @param username The username
* @param password The password to set
* @return true if successful, false if user doesn't exist
*/
public boolean setPassword(String username, String password) {
UserAccount account = accounts.get(username.trim());
if (account == null) {
return false;
}
UserAccount updatedAccount = new UserAccount(
account.username(),
account.email(),
password,
account.difficultyLevel(),
account.registrationDate(),
true); // Now registered
accounts.put(username.trim(), updatedAccount);
return true;
}
/**
* Changes the password for an existing user.
*
* @param username The username
* @param oldPassword The current password
* @param newPassword The new password
* @return true if successful, false if old password is incorrect or user doesn't exist
*/
public boolean changePassword(String username, String oldPassword, String newPassword) {
UserAccount account = accounts.get(username.trim());
if (account == null || !account.password().equals(oldPassword) || !account.isRegistered()) {
return false;
}
UserAccount updatedAccount = new UserAccount(
account.username(),
account.email(),
newPassword,
account.difficultyLevel(),
account.registrationDate(),
true);
accounts.put(username.trim(), updatedAccount);
return true;
}
/**
* Checks if a user exists in the system.
*
* @param username The username to check
* @return true if user exists, false otherwise
*/
public boolean userExists(String username) {
return accounts.containsKey(username.trim());
}
/**
* Gets a user account by username.
*
* @param username The username
* @return Optional containing the user account if found
*/
public Optional<UserAccount> getUser(String username) {
return Optional.ofNullable(accounts.get(username.trim()));
}
}

@ -1,62 +0,0 @@
package com.personalproject.auth;
import java.util.Random;
/**
* Interface for sending emails with registration codes.
*/
public final class EmailService {
private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
private static final int CODE_LENGTH = 6;
private static final Random RANDOM = new Random();
private EmailService() {
// Prevent instantiation of utility class
}
/**
* Generates a random registration code.
*
* @return A randomly generated registration code
*/
public static String generateRegistrationCode() {
StringBuilder code = new StringBuilder();
for (int i = 0; i < CODE_LENGTH; i++) {
code.append(CHARACTERS.charAt(RANDOM.nextInt(CHARACTERS.length())));
}
return code.toString();
}
/**
* Sends a registration code to the specified email address. In a real implementation, this would
* connect to an email server.
*
* @param email The email address to send the code to
* @param registrationCode The registration code to send
* @return true if successfully sent (in this mock implementation, always true)
*/
public static boolean sendRegistrationCode(String email, String registrationCode) {
// In a real implementation, this would connect to an email server
// For the mock implementation, we'll just print to console
System.out.println("Sending registration code " + registrationCode + " to " + email);
return true;
}
/**
* Validates if an email address has a valid format.
*
* @param email The email address to validate
* @return true if the email has valid format, false otherwise
*/
public static boolean isValidEmail(String email) {
if (email == null || email.trim().isEmpty()) {
return false;
}
// Simple email validation using regex
String emailRegex = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@"
+ "(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";
return email.matches(emailRegex);
}
}

@ -1,30 +0,0 @@
package com.personalproject.auth;
import java.util.regex.Pattern;
/**
* Utility class for password validation.
*/
public final class PasswordValidator {
private static final Pattern PASSWORD_PATTERN =
Pattern.compile("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)[a-zA-Z\\d]{6,10}$");
private PasswordValidator() {
// Prevent instantiation of utility class
}
/**
* Validates if a password meets the requirements: - 6-10 characters - Contains at least one
* uppercase letter - Contains at least one lowercase letter - Contains at least one digit.
*
* @param password The password to validate
* @return true if password meets requirements, false otherwise
*/
public static boolean isValidPassword(String password) {
if (password == null) {
return false;
}
return PASSWORD_PATTERN.matcher(password).matches();
}
}

@ -1,40 +0,0 @@
package com.personalproject.auth;
import com.personalproject.model.DifficultyLevel;
import java.time.LocalDateTime;
/**
* .
*/
public record UserAccount(
String username,
String email,
String password,
DifficultyLevel difficultyLevel,
LocalDateTime registrationDate,
boolean isRegistered) {
/**
* Creates a new user account with registration date set to now.
*
* @param username The username
* @param email The email address
* @param password The password
* @param difficultyLevel The selected difficulty level
* @param isRegistered Whether the user has completed registration
*/
public UserAccount {
if (username == null || username.trim().isEmpty()) {
throw new IllegalArgumentException("Username cannot be null or empty");
}
if (email == null || email.trim().isEmpty()) {
throw new IllegalArgumentException("Email cannot be null or empty");
}
if (password == null) {
throw new IllegalArgumentException("Password cannot be null");
}
if (difficultyLevel == null) {
throw new IllegalArgumentException("Difficulty level cannot be null");
}
}
}

@ -1,145 +0,0 @@
package com.personalproject.controller;
import com.personalproject.generator.QuestionGenerator;
import com.personalproject.model.DifficultyLevel;
import com.personalproject.model.ExamSession;
import com.personalproject.service.ExamResultService;
import com.personalproject.service.MathLearningService;
import com.personalproject.service.QuestionGenerationService;
import java.util.Map;
import java.util.Optional;
/**
* MVC.
*/
public final class MathLearningController {
private final MathLearningService mathLearningService;
/**
* .
*
* @param generatorMap
* @param questionGenerationService
*/
public MathLearningController(
Map<DifficultyLevel, QuestionGenerator> generatorMap,
QuestionGenerationService questionGenerationService) {
this.mathLearningService = new MathLearningService(generatorMap, questionGenerationService);
}
/**
* .
*
* @param username
* @param email
* @param difficultyLevel
* @return truefalse
*/
public boolean initiateRegistration(String username, String email,
DifficultyLevel difficultyLevel) {
return mathLearningService.initiateRegistration(username, email, difficultyLevel);
}
/**
* .
*
* @param username
* @param registrationCode
* @return truefalse
*/
public boolean verifyRegistrationCode(String username, String registrationCode) {
return mathLearningService.verifyRegistrationCode(username, registrationCode);
}
/**
* .
*
* @param username
* @param password
* @return truefalse
*/
public boolean setPassword(String username, String password) {
return mathLearningService.setPassword(username, password);
}
/**
* .
*
* @param username
* @param password
* @return Optional
*/
public Optional<com.personalproject.auth.UserAccount> authenticate(String username,
String password) {
return mathLearningService.authenticate(username, password);
}
/**
* .
*
* @param username
* @param difficultyLevel
* @param questionCount
* @return
*/
public ExamSession createExamSession(String username, DifficultyLevel difficultyLevel,
int questionCount) {
return mathLearningService.createExamSession(username, difficultyLevel, questionCount);
}
/**
* .
*
* @param examSession
*/
public void saveExamResults(ExamSession examSession) {
mathLearningService.saveExamResults(examSession);
}
/**
* .
*
* @param examSession
* @param continueWithSameLevel
* @param newDifficultyLevel null
* @return
*/
public ExamResultService.ExamContinuationAction processExamResult(
ExamSession examSession, boolean continueWithSameLevel, DifficultyLevel newDifficultyLevel) {
return mathLearningService.processExamResult(examSession, continueWithSameLevel,
newDifficultyLevel);
}
/**
* .
*
* @param username
* @param oldPassword
* @param newPassword
* @return truefalse
*/
public boolean changePassword(String username, String oldPassword, String newPassword) {
return mathLearningService.changePassword(username, oldPassword, newPassword);
}
/**
* .
*
* @param password
* @return truefalse
*/
public boolean isValidPassword(String password) {
return MathLearningService.isValidPassword(password);
}
/**
* .
*
* @param email
* @return truefalse
*/
public boolean isValidEmail(String email) {
return MathLearningService.isValidEmail(email);
}
}

@ -1,37 +0,0 @@
package com.personalproject.generator;
import java.util.Random;
/**
* .
*/
public final class HighSchoolQuestionGenerator implements QuestionGenerator {
private static final String[] OPERATORS = {"+", "-", "*", "/"};
private static final String[] TRIG_FUNCTIONS = {"sin", "cos", "tan"};
@Override
public String generateQuestion(Random random) {
int operandCount = random.nextInt(5) + 1;
String[] operands = new String[operandCount];
for (int index = 0; index < operandCount; index++) {
operands[index] = String.valueOf(random.nextInt(100) + 1);
}
int specialIndex = random.nextInt(operandCount);
String function = TRIG_FUNCTIONS[random.nextInt(TRIG_FUNCTIONS.length)];
operands[specialIndex] = function + '(' + operands[specialIndex] + ')';
StringBuilder builder = new StringBuilder();
for (int index = 0; index < operandCount; index++) {
if (index > 0) {
String operator = OPERATORS[random.nextInt(OPERATORS.length)];
builder.append(' ').append(operator).append(' ');
}
builder.append(operands[index]);
}
String expression = builder.toString();
if (operandCount > 1 && random.nextBoolean()) {
return '(' + expression + ')';
}
return expression;
}
}

@ -1,39 +0,0 @@
package com.personalproject.generator;
import java.util.Random;
/**
* .
*/
public final class MiddleSchoolQuestionGenerator implements QuestionGenerator {
private static final String[] OPERATORS = {"+", "-", "*", "/"};
@Override
public String generateQuestion(Random random) {
int operandCount = random.nextInt(5) + 1;
String[] operands = new String[operandCount];
for (int index = 0; index < operandCount; index++) {
operands[index] = String.valueOf(random.nextInt(100) + 1);
}
int specialIndex = random.nextInt(operandCount);
if (random.nextBoolean()) {
operands[specialIndex] = '(' + operands[specialIndex] + ")^2";
} else {
operands[specialIndex] = "sqrt(" + operands[specialIndex] + ')';
}
StringBuilder builder = new StringBuilder();
for (int index = 0; index < operandCount; index++) {
if (index > 0) {
String operator = OPERATORS[random.nextInt(OPERATORS.length)];
builder.append(' ').append(operator).append(' ');
}
builder.append(operands[index]);
}
String expression = builder.toString();
if (operandCount > 1 && random.nextBoolean()) {
return '(' + expression + ')';
}
return expression;
}
}

@ -1,31 +0,0 @@
package com.personalproject.generator;
import java.util.Random;
/**
* .
*/
public final class PrimaryQuestionGenerator implements QuestionGenerator {
private static final String[] OPERATORS = {"+", "-", "*", "/"};
@Override
public String generateQuestion(Random random) {
// 至少生成两个操作数,避免题目退化成单个数字
int operandCount = random.nextInt(4) + 2;
StringBuilder builder = new StringBuilder();
for (int index = 0; index < operandCount; index++) {
if (index > 0) {
String operator = OPERATORS[random.nextInt(OPERATORS.length)];
builder.append(' ').append(operator).append(' ');
}
int value = random.nextInt(100) + 1;
builder.append(value);
}
String expression = builder.toString();
if (operandCount > 1 && random.nextBoolean()) {
return '(' + expression + ')';
}
return expression;
}
}

@ -1,17 +0,0 @@
package com.personalproject.generator;
import java.util.Random;
/**
* .
*/
public interface QuestionGenerator {
/**
* .
*
* @param random .
* @return .
*/
String generateQuestion(Random random);
}

@ -1,49 +0,0 @@
package com.personalproject.model;
import java.util.Optional;
/**
* .
*/
public enum DifficultyLevel {
PRIMARY("小学"),
MIDDLE("初中"),
HIGH("高中");
private final String displayName;
DifficultyLevel(String displayName) {
this.displayName = displayName;
}
/**
* .
*
* @return .
*/
public String getDisplayName() {
return displayName;
}
/**
* .
*
* @param name .
* @return .
*/
public static Optional<DifficultyLevel> fromDisplayName(String name) {
if (name == null) {
return Optional.empty();
}
String trimmed = name.trim();
if (trimmed.isEmpty()) {
return Optional.empty();
}
for (DifficultyLevel level : values()) {
if (level.displayName.equals(trimmed)) {
return Optional.of(level);
}
}
return Optional.empty();
}
}

@ -1,195 +0,0 @@
package com.personalproject.model;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
/**
* Represents an exam session for a user.
*/
public final class ExamSession {
private final String username;
private final DifficultyLevel difficultyLevel;
private final List<QuizQuestion> questions;
private final List<Integer> userAnswers;
private final LocalDateTime startTime;
private int currentQuestionIndex;
/**
* Creates a new exam session.
*
* @param username The username of the test taker
* @param difficultyLevel The difficulty level of the exam
* @param questions The list of questions for the exam
*/
public ExamSession(String username, DifficultyLevel difficultyLevel,
List<QuizQuestion> questions) {
if (username == null || username.trim().isEmpty()) {
throw new IllegalArgumentException("Username cannot be null or empty");
}
if (difficultyLevel == null) {
throw new IllegalArgumentException("Difficulty level cannot be null");
}
if (questions == null || questions.isEmpty()) {
throw new IllegalArgumentException("Questions list cannot be null or empty");
}
this.username = username;
this.difficultyLevel = difficultyLevel;
this.questions = List.copyOf(questions); // Immutable copy of questions
this.userAnswers = new ArrayList<>();
// Initialize user answers with -1 (no answer selected)
for (int i = 0; i < questions.size(); i++) {
userAnswers.add(-1);
}
this.startTime = LocalDateTime.now();
this.currentQuestionIndex = 0;
}
/**
* Gets the username of the test taker.
*
* @return The username
*/
public String getUsername() {
return username;
}
/**
* Gets the difficulty level of the exam.
*
* @return The difficulty level
*/
public DifficultyLevel getDifficultyLevel() {
return difficultyLevel;
}
/**
* Gets the list of questions in the exam.
*
* @return An unmodifiable list of questions
*/
public List<QuizQuestion> getQuestions() {
return questions;
}
/**
* Gets the user's answers to the questions.
*
* @return A list of answer indices (-1 means no answer selected)
*/
public List<Integer> getUserAnswers() {
return List.copyOf(userAnswers); // Return a copy to prevent modification
}
/**
* Gets the current question index.
*
* @return The current question index
*/
public int getCurrentQuestionIndex() {
return currentQuestionIndex;
}
/**
* Sets the user's answer for the current question.
*
* @param answerIndex The index of the selected answer
*/
public void setAnswer(int answerIndex) {
if (currentQuestionIndex < 0 || currentQuestionIndex >= questions.size()) {
throw new IllegalStateException("No valid question at current index");
}
if (answerIndex < 0 || answerIndex > questions.get(currentQuestionIndex).getOptions().size()) {
throw new IllegalArgumentException("Invalid answer index");
}
userAnswers.set(currentQuestionIndex, answerIndex);
}
/**
* Moves to the next question.
*
* @return true if successfully moved to next question, false if already at the last question
*/
public boolean goToNextQuestion() {
if (currentQuestionIndex < questions.size() - 1) {
currentQuestionIndex++;
return true;
}
return false;
}
/**
* Moves to the previous question.
*
* @return true if successfully moved to previous question, false if already at the first question
*/
public boolean goToPreviousQuestion() {
if (currentQuestionIndex > 0) {
currentQuestionIndex--;
return true;
}
return false;
}
/**
* Checks if the exam is complete (all questions answered or at the end).
*
* @return true if the exam is complete, false otherwise
*/
public boolean isComplete() {
return currentQuestionIndex >= questions.size() - 1;
}
/**
* Gets the current question.
*
* @return The current quiz question
*/
public QuizQuestion getCurrentQuestion() {
if (currentQuestionIndex < 0 || currentQuestionIndex >= questions.size()) {
throw new IllegalStateException("No valid question at current index");
}
return questions.get(currentQuestionIndex);
}
/**
* Gets the user's answer for a specific question.
*
* @param questionIndex The index of the question
* @return The index of the user's answer (or -1 if no answer selected)
*/
public int getUserAnswer(int questionIndex) {
if (questionIndex < 0 || questionIndex >= questions.size()) {
throw new IllegalArgumentException("Question index out of bounds");
}
return userAnswers.get(questionIndex);
}
/**
* Calculates the score as a percentage.
*
* @return The score as a percentage (0-100)
*/
public double calculateScore() {
int correctCount = 0;
for (int i = 0; i < questions.size(); i++) {
QuizQuestion question = questions.get(i);
int userAnswer = userAnswers.get(i);
if (userAnswer != -1 && question.isAnswerCorrect(userAnswer)) {
correctCount++;
}
}
return questions.isEmpty() ? 0.0 : (double) correctCount / questions.size() * 100.0;
}
/**
* Gets the start time of the exam.
*
* @return The start time
*/
public LocalDateTime getStartTime() {
return startTime;
}
}

@ -1,73 +0,0 @@
package com.personalproject.model;
import java.util.List;
/**
* Represents a quiz question with multiple choice options.
*/
public final class QuizQuestion {
private final String questionText;
private final List<String> options;
private final int correctAnswerIndex;
/**
* Creates a new quiz question.
*
* @param questionText The text of the question
* @param options The list of answer options
* @param correctAnswerIndex The index of the correct answer in the options list
*/
public QuizQuestion(String questionText, List<String> options, int correctAnswerIndex) {
if (questionText == null || questionText.trim().isEmpty()) {
throw new IllegalArgumentException("Question text cannot be null or empty");
}
if (options == null || options.size() < 2) {
throw new IllegalArgumentException("Options must contain at least 2 choices");
}
if (correctAnswerIndex < 0 || correctAnswerIndex >= options.size()) {
throw new IllegalArgumentException("Correct answer index out of bounds");
}
this.questionText = questionText;
this.options = List.copyOf(options); // Immutable copy
this.correctAnswerIndex = correctAnswerIndex;
}
/**
* Gets the question text.
*
* @return The question text
*/
public String getQuestionText() {
return questionText;
}
/**
* Gets the list of answer options.
*
* @return An unmodifiable list of answer options
*/
public List<String> getOptions() {
return options;
}
/**
* Gets the index of the correct answer in the options list.
*
* @return The index of the correct answer
*/
public int getCorrectAnswerIndex() {
return correctAnswerIndex;
}
/**
* Checks if the given answer index matches the correct answer.
*
* @param answerIndex The index of the user's answer
* @return true if the answer is correct, false otherwise
*/
public boolean isAnswerCorrect(int answerIndex) {
return answerIndex == correctAnswerIndex;
}
}

@ -1,83 +0,0 @@
package com.personalproject.service;
import com.personalproject.model.DifficultyLevel;
import com.personalproject.model.ExamSession;
/**
* 退.
*/
public final class ExamResultService {
/**
* .
*
* @param examSession
* @param continueWithSameLevel 使
* @param newDifficultyLevel null
* @return
*/
public ExamContinuationAction processExamResult(
ExamSession examSession, boolean continueWithSameLevel, DifficultyLevel newDifficultyLevel) {
if (continueWithSameLevel) {
return new ExamContinuationAction(
true, examSession.getDifficultyLevel(), (int) examSession.getQuestions().size());
} else if (newDifficultyLevel != null) {
return new ExamContinuationAction(true, newDifficultyLevel,
(int) examSession.getQuestions().size());
} else {
return new ExamContinuationAction(false, null, 0);
}
}
/**
* .
*/
public static final class ExamContinuationAction {
private final boolean shouldContinue;
private final DifficultyLevel nextDifficultyLevel;
private final int nextQuestionCount;
/**
* .
*
* @param shouldContinue
* @param nextDifficultyLevel null
* @param nextQuestionCount 0
*/
public ExamContinuationAction(
boolean shouldContinue, DifficultyLevel nextDifficultyLevel, int nextQuestionCount) {
this.shouldContinue = shouldContinue;
this.nextDifficultyLevel = nextDifficultyLevel;
this.nextQuestionCount = nextQuestionCount;
}
/**
* .
*
* @return true退false
*/
public boolean shouldContinue() {
return shouldContinue;
}
/**
* .
*
* @return null
*/
public DifficultyLevel getNextDifficultyLevel() {
return nextDifficultyLevel;
}
/**
* .
*
* @return 0
*/
public int getNextQuestionCount() {
return nextQuestionCount;
}
}
}

@ -1,140 +0,0 @@
package com.personalproject.service;
import com.personalproject.generator.QuestionGenerator;
import com.personalproject.model.DifficultyLevel;
import com.personalproject.model.ExamSession;
import com.personalproject.model.QuizQuestion;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
/**
* .
*/
public final class ExamService {
private static final int OPTIONS_COUNT = 4;
private final Map<DifficultyLevel, QuestionGenerator> generators;
private final Random random = new Random();
private final QuestionGenerationService questionGenerationService;
/**
* .
*
* @param generatorMap
* @param questionGenerationService
*/
public ExamService(
Map<DifficultyLevel, QuestionGenerator> generatorMap,
QuestionGenerationService questionGenerationService) {
this.generators = new EnumMap<>(DifficultyLevel.class);
this.generators.putAll(generatorMap);
this.questionGenerationService = questionGenerationService;
}
/**
* 使.
*
* @param username
* @param difficultyLevel
* @param questionCount
* @return
*/
public ExamSession createExamSession(
String username, DifficultyLevel difficultyLevel, int questionCount) {
if (questionCount < 10 || questionCount > 30) {
throw new IllegalArgumentException("题目数量必须在10到30之间");
}
// 根据难度级别生成题目
List<String> generatedQuestions = new ArrayList<>();
QuestionGenerator generator = generators.get(difficultyLevel);
if (generator == null) {
throw new IllegalArgumentException("找不到难度级别的生成器: " + difficultyLevel);
}
for (int i = 0; i < questionCount; i++) {
String question = generator.generateQuestion(random);
generatedQuestions.add(question);
}
// 将字符串题目转换为带有选项和答案的QuizQuestion对象
List<QuizQuestion> quizQuestions = new ArrayList<>();
for (String questionText : generatedQuestions) {
List<String> options = generateOptions(questionText);
int correctAnswerIndex = generateCorrectAnswerIndex(options.size());
QuizQuestion quizQuestion = new QuizQuestion(questionText, options, correctAnswerIndex);
quizQuestions.add(quizQuestion);
}
return new ExamSession(username, difficultyLevel, quizQuestions);
}
/**
* 使.
*
* @param username
* @param difficultyLevel
* @param questions
* @return
*/
public ExamSession createExamSession(
String username, DifficultyLevel difficultyLevel, List<QuizQuestion> questions) {
if (questions.size() < 10 || questions.size() > 30) {
throw new IllegalArgumentException("题目数量必须在10到30之间");
}
return new ExamSession(username, difficultyLevel, questions);
}
/**
* . - .
*
* @param questionText
* @return
*/
private List<String> generateOptions(String questionText) {
List<String> options = new ArrayList<>();
// 为每个题目生成4个选项
try {
// 尝试将数学表达式作为正确答案进行评估
double correctAnswer = MathExpressionEvaluator.evaluate(questionText);
// 创建正确答案选项
options.add(String.format("%.2f", correctAnswer));
// 生成3个错误选项
for (int i = 0; i < OPTIONS_COUNT - 1; i++) {
double incorrectAnswer = correctAnswer + (random.nextGaussian() * 10); // 添加一些随机偏移
if (Math.abs(incorrectAnswer - correctAnswer) < 0.1) { // 确保不同
incorrectAnswer += 1.5;
}
options.add(String.format("%.2f", incorrectAnswer));
}
} catch (Exception e) {
// 如果评估失败,创建虚拟选项
for (int i = 0; i < OPTIONS_COUNT; i++) {
options.add("选项 " + (i + 1));
}
}
// 随机打乱选项以随机化正确答案的位置
java.util.Collections.shuffle(options, random);
// 找到打乱后的正确答案索引
// 对于此模拟实现,我们将返回第一个选项(索引0)作为正确答案
// 实际实现将跟踪正确答案
return options;
}
/**
* .
*
* @param optionCount
* @return 0optionCount-1
*/
private int generateCorrectAnswerIndex(int optionCount) {
return random.nextInt(optionCount);
}
}

@ -1,217 +0,0 @@
package com.personalproject.service;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
import java.util.regex.Pattern;
/**
* A mathematical expression evaluator that can handle basic arithmetic operations.
*/
public final class MathExpressionEvaluator {
private static final Pattern NUMBER_PATTERN = Pattern.compile("-?\\d+(\\.\\d+)?");
private static final Map<Character, Integer> PRECEDENCE = new HashMap<>();
static {
PRECEDENCE.put('+', 1);
PRECEDENCE.put('-', 1);
PRECEDENCE.put('*', 2);
PRECEDENCE.put('/', 2);
PRECEDENCE.put('^', 3);
}
private MathExpressionEvaluator() {
// Prevent instantiation of utility class
}
/**
* Evaluates a mathematical expression string.
*
* @param expression The mathematical expression to evaluate
* @return The result of the evaluation
* @throws IllegalArgumentException If the expression is invalid
*/
public static double evaluate(String expression) {
if (expression == null) {
throw new IllegalArgumentException("Expression cannot be null");
}
expression = expression.replaceAll("\\s+", ""); // Remove whitespace
if (expression.isEmpty()) {
throw new IllegalArgumentException("Expression cannot be empty");
}
// Tokenize the expression
String[] tokens = tokenize(expression);
// Convert infix to postfix notation using Shunting Yard algorithm
String[] postfix = infixToPostfix(tokens);
// Evaluate the postfix expression
return evaluatePostfix(postfix);
}
/**
* Tokenizes the expression into numbers and operators.
*
* @param expression The expression to tokenize
* @return An array of tokens
*/
private static String[] tokenize(String expression) {
java.util.List<String> tokens = new java.util.ArrayList<>();
StringBuilder currentNumber = new StringBuilder();
for (int i = 0; i < expression.length(); i++) {
char c = expression.charAt(i);
if (Character.isDigit(c) || c == '.') {
currentNumber.append(c);
} else if (c == '(' || c == ')') {
if (currentNumber.length() > 0) {
tokens.add(currentNumber.toString());
currentNumber.setLength(0);
}
tokens.add(String.valueOf(c));
} else if (isOperator(c)) {
if (currentNumber.length() > 0) {
tokens.add(currentNumber.toString());
currentNumber.setLength(0);
}
// Handle unary minus
if (c == '-' && (i == 0 || expression.charAt(i - 1) == '(')) {
currentNumber.append(c);
} else {
tokens.add(String.valueOf(c));
}
} else {
throw new IllegalArgumentException("Invalid character in expression: " + c);
}
}
if (currentNumber.length() > 0) {
tokens.add(currentNumber.toString());
}
return tokens.toArray(new String[0]);
}
/**
* Checks if the character is an operator.
*
* @param c The character to check
* @return true if the character is an operator, false otherwise
*/
private static boolean isOperator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/' || c == '^';
}
/**
* Converts infix notation to postfix notation using the Shunting Yard algorithm.
*
* @param tokens The tokens in infix notation
* @return An array of tokens in postfix notation
*/
private static String[] infixToPostfix(String[] tokens) {
java.util.List<String> output = new java.util.ArrayList<>();
Stack<String> operators = new Stack<>();
for (String token : tokens) {
if (isNumber(token)) {
output.add(token);
} else if (token.equals("(")) {
operators.push(token);
} else if (token.equals(")")) {
while (!operators.isEmpty() && !operators.peek().equals("(")) {
output.add(operators.pop());
}
if (!operators.isEmpty()) {
operators.pop(); // Remove the "("
}
} else if (isOperator(token.charAt(0))) {
while (!operators.isEmpty()
&& isOperator(operators.peek().charAt(0))
&& PRECEDENCE.get(operators.peek().charAt(0)) >= PRECEDENCE.get(token.charAt(0))) {
output.add(operators.pop());
}
operators.push(token);
}
}
while (!operators.isEmpty()) {
output.add(operators.pop());
}
return output.toArray(new String[0]);
}
/**
* Evaluates a postfix expression.
*
* @param postfix The tokens in postfix notation
* @return The result of the evaluation
*/
private static double evaluatePostfix(String[] postfix) {
Stack<Double> values = new Stack<>();
for (String token : postfix) {
if (isNumber(token)) {
values.push(Double.parseDouble(token));
} else if (isOperator(token.charAt(0))) {
if (values.size() < 2) {
throw new IllegalArgumentException("Invalid expression: insufficient operands");
}
double b = values.pop();
double a = values.pop();
double result = performOperation(a, b, token.charAt(0));
values.push(result);
}
}
if (values.size() != 1) {
throw new IllegalArgumentException("Invalid expression: too many operands");
}
return values.pop();
}
/**
* Performs the specified operation on the two operands.
*
* @param a The first operand
* @param b The second operand
* @param operator The operator to apply
* @return The result of the operation
*/
private static double performOperation(double a, double b, char operator) {
switch (operator) {
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
if (b == 0) {
throw new ArithmeticException("Division by zero");
}
return a / b;
case '^':
return Math.pow(a, b);
default:
throw new IllegalArgumentException("Unknown operator: " + operator);
}
}
/**
* Checks if the token is a number.
*
* @param token The token to check
* @return true if the token is a number, false otherwise
*/
private static boolean isNumber(String token) {
return NUMBER_PATTERN.matcher(token).matches();
}
}

@ -1,170 +0,0 @@
package com.personalproject.service;
import com.personalproject.auth.AccountRepository;
import com.personalproject.auth.EmailService;
import com.personalproject.auth.PasswordValidator;
import com.personalproject.generator.QuestionGenerator;
import com.personalproject.model.DifficultyLevel;
import com.personalproject.model.ExamSession;
import com.personalproject.storage.QuestionStorageService;
import java.util.Map;
import java.util.Optional;
/**
* JavaFX UI. UIAPI.
*/
public final class MathLearningService {
private final AccountRepository accountRepository;
private final RegistrationService registrationService;
private final ExamService examService;
private final QuestionStorageService storageService;
private final ExamResultService resultService;
/**
* .
*
* @param generatorMap
* @param questionGenerationService
*/
public MathLearningService(
Map<DifficultyLevel, QuestionGenerator> generatorMap,
QuestionGenerationService questionGenerationService) {
this.accountRepository = new AccountRepository();
this.registrationService = new RegistrationService(accountRepository);
this.examService = new ExamService(generatorMap, questionGenerationService);
this.storageService = new QuestionStorageService();
this.resultService = new ExamResultService();
}
// 注册方法
/**
* .
*
* @param username
* @param email
* @param difficultyLevel
* @return truefalse
*/
public boolean initiateRegistration(String username, String email,
DifficultyLevel difficultyLevel) {
return registrationService.initiateRegistration(username, email, difficultyLevel);
}
/**
* .
*
* @param username
* @param registrationCode
* @return truefalse
*/
public boolean verifyRegistrationCode(String username, String registrationCode) {
return registrationService.verifyRegistrationCode(username, registrationCode);
}
/**
* .
*
* @param username
* @param password
* @return truefalse
*/
public boolean setPassword(String username, String password) {
return registrationService.setPassword(username, password);
}
/**
* 使.
*
* @param username
* @param password
* @return Optional
*/
public Optional<com.personalproject.auth.UserAccount> authenticate(String username,
String password) {
return registrationService.authenticate(username, password);
}
/**
* .
*
* @param password
* @return truefalse
*/
public static boolean isValidPassword(String password) {
return PasswordValidator.isValidPassword(password);
}
/**
* .
*
* @param username
* @param oldPassword
* @param newPassword
* @return truefalse
*/
public boolean changePassword(String username, String oldPassword, String newPassword) {
return registrationService.changePassword(username, oldPassword, newPassword);
}
/**
* .
*
* @param email
* @return truefalse
*/
public static boolean isValidEmail(String email) {
return EmailService.isValidEmail(email);
}
/**
* .
*
* @param username
* @param difficultyLevel
* @param questionCount
* @return
*/
public ExamSession createExamSession(String username, DifficultyLevel difficultyLevel,
int questionCount) {
return examService.createExamSession(username, difficultyLevel, questionCount);
}
/**
* .
*
* @param examSession
* @return
*/
public java.nio.file.Path saveExamResults(ExamSession examSession) {
try {
return storageService.saveExamResults(examSession);
} catch (java.io.IOException e) {
throw new RuntimeException("保存考试结果失败", e);
}
}
/**
* .
*
* @param examSession
* @param continueWithSameLevel 使
* @param newDifficultyLevel null
* @return
*/
public ExamResultService.ExamContinuationAction processExamResult(
ExamSession examSession, boolean continueWithSameLevel, DifficultyLevel newDifficultyLevel) {
return resultService.processExamResult(examSession, continueWithSameLevel, newDifficultyLevel);
}
/**
* .
*
* @param username
* @return truefalse
*/
public boolean userExists(String username) {
return registrationService.userExists(username);
}
}

@ -1,71 +0,0 @@
package com.personalproject.service;
import com.personalproject.generator.QuestionGenerator;
import com.personalproject.model.DifficultyLevel;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
/**
* .
*/
public final class QuestionGenerationService {
private static final int MAX_ATTEMPTS = 10_000;
private final Map<DifficultyLevel, QuestionGenerator> generators;
private final Random random = new SecureRandom();
/**
* .
*
* @param generatorMap .
*/
public QuestionGenerationService(Map<DifficultyLevel, QuestionGenerator> generatorMap) {
generators = new EnumMap<>(DifficultyLevel.class);
generators.putAll(generatorMap);
}
/**
* .
*
* @param level .
* @param count .
* @param existingQuestions .
* @return .
* @throws IllegalArgumentException .
* @throws IllegalStateException .
*/
public List<String> generateUniqueQuestions(
DifficultyLevel level, int count, Set<String> existingQuestions) {
QuestionGenerator generator = generators.get(level);
if (generator == null) {
throw new IllegalArgumentException("Unsupported difficulty level: " + level);
}
Set<String> produced = new HashSet<>();
List<String> results = new ArrayList<>();
int attempts = 0;
while (results.size() < count) {
if (attempts >= MAX_ATTEMPTS) {
throw new IllegalStateException("Unable to generate enough unique questions.");
}
attempts++;
String question = generator.generateQuestion(random).trim();
if (question.isEmpty()) {
continue;
}
if (existingQuestions.contains(question)) {
continue;
}
if (!produced.add(question)) {
continue;
}
results.add(question);
}
return results;
}
}

@ -1,138 +0,0 @@
package com.personalproject.service;
import com.personalproject.auth.AccountRepository;
import com.personalproject.auth.EmailService;
import com.personalproject.auth.PasswordValidator;
import com.personalproject.model.DifficultyLevel;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
/**
* .
*/
public final class RegistrationService {
private final AccountRepository accountRepository;
private final Map<String, String> pendingRegistrations;
private final Map<String, Integer> registrationAttempts;
/**
* .
*
* @param accountRepository 使
*/
public RegistrationService(AccountRepository accountRepository) {
this.accountRepository = accountRepository;
this.pendingRegistrations = new ConcurrentHashMap<>();
this.registrationAttempts = new ConcurrentHashMap<>();
}
/**
* .
*
* @param username
* @param email
* @param difficultyLevel
* @return truefalse
*/
public boolean initiateRegistration(String username, String email,
DifficultyLevel difficultyLevel) {
if (!EmailService.isValidEmail(email)) {
return false;
}
if (!accountRepository.registerUser(username, email, difficultyLevel)) {
return false; // 用户名已存在或邮箱已注册
}
String registrationCode = EmailService.generateRegistrationCode();
pendingRegistrations.put(username, registrationCode);
registrationAttempts.put(username, 0);
return EmailService.sendRegistrationCode(email, registrationCode);
}
/**
* .
*
* @param username
* @param registrationCode
* @return truefalse
*/
public boolean verifyRegistrationCode(String username, String registrationCode) {
String storedCode = pendingRegistrations.get(username);
if (storedCode == null || !storedCode.equals(registrationCode)) {
// 跟踪失败尝试
int attempts = registrationAttempts.getOrDefault(username, 0);
attempts++;
registrationAttempts.put(username, attempts);
if (attempts >= 3) {
// 如果失败次数过多,则删除用户
pendingRegistrations.remove(username);
registrationAttempts.remove(username);
return false;
}
return false;
}
// 有效码,从待处理列表中移除
pendingRegistrations.remove(username);
registrationAttempts.remove(username);
return true;
}
/**
* .
*
* @param username
* @param password
* @return truefalse
*/
public boolean setPassword(String username, String password) {
if (!PasswordValidator.isValidPassword(password)) {
return false;
}
return accountRepository.setPassword(username, password);
}
/**
* .
*
* @param username
* @param oldPassword
* @param newPassword
* @return truefalse
*/
public boolean changePassword(String username, String oldPassword, String newPassword) {
if (!PasswordValidator.isValidPassword(newPassword)) {
return false;
}
return accountRepository.changePassword(username, oldPassword, newPassword);
}
/**
* 使.
*
* @param username
* @param password
* @return Optional
*/
public Optional<com.personalproject.auth.UserAccount> authenticate(String username,
String password) {
return accountRepository.authenticate(username, password);
}
/**
* .
*
* @param username
* @return truefalse
*/
public boolean userExists(String username) {
return accountRepository.userExists(username);
}
}

@ -1,162 +0,0 @@
package com.personalproject.storage;
import com.personalproject.model.ExamSession;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Stream;
/**
* .
*/
public final class QuestionStorageService {
private static final String BASE_DIRECTORY = "user_data";
private static final String QUESTIONS_SUBDIR = "questions";
private static final String RESULTS_SUBDIR = "results";
private static final DateTimeFormatter FORMATTER =
DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm-ss");
/**
* .
*
* @param username .
* @return .
* @throws IOException I/O .
*/
public Set<String> loadExistingQuestions(String username) throws IOException {
Path accountDirectory = getQuestionsDirectory(username);
Set<String> questions = new HashSet<>();
if (!Files.exists(accountDirectory)) {
return questions;
}
try (Stream<Path> paths = Files.list(accountDirectory)) {
paths
.filter(path -> path.getFileName().toString().endsWith(".txt"))
.sorted()
.forEach(path -> readQuestionsFromFile(path, questions));
}
return questions;
}
/**
* .
*
* @param username .
* @param questions .
* @return .
* @throws IOException .
*/
public Path saveQuestions(String username, List<String> questions) throws IOException {
Path accountDirectory = getQuestionsDirectory(username);
Files.createDirectories(accountDirectory);
String fileName = FORMATTER.format(LocalDateTime.now()) + ".txt";
Path outputFile = accountDirectory.resolve(fileName);
StringBuilder builder = new StringBuilder();
for (int index = 0; index < questions.size(); index++) {
String question = questions.get(index);
builder
.append(index + 1)
.append(". ")
.append(question)
.append(System.lineSeparator())
.append(System.lineSeparator());
}
Files.writeString(
outputFile, builder.toString(), StandardCharsets.UTF_8, StandardOpenOption.CREATE_NEW);
return outputFile;
}
/**
* .
*
* @param examSession
* @return
* @throws IOException
*/
public Path saveExamResults(ExamSession examSession) throws IOException {
Path resultsDirectory = getResultsDirectory(examSession.getUsername());
Files.createDirectories(resultsDirectory);
StringBuilder builder = new StringBuilder();
builder.append("考试结果报告").append(System.lineSeparator());
builder.append("用户名: ").append(examSession.getUsername()).append(System.lineSeparator());
builder.append("难度: ").append(examSession.getDifficultyLevel().getDisplayName())
.append(System.lineSeparator());
builder.append("开始时间: ").append(examSession.getStartTime()).append(System.lineSeparator());
builder.append("题目数量: ").append(examSession.getQuestions().size())
.append(System.lineSeparator());
builder.append("得分: ").append(String.format("%.2f", examSession.calculateScore())).append("%")
.append(System.lineSeparator());
builder.append(System.lineSeparator());
// 添加逐题结果
for (int i = 0; i < examSession.getQuestions().size(); i++) {
var question = examSession.getQuestions().get(i);
int userAnswer = examSession.getUserAnswer(i);
boolean isCorrect = question.isAnswerCorrect(userAnswer);
builder.append("题目 ").append(i + 1).append(": ").append(question.getQuestionText())
.append(System.lineSeparator());
builder.append("您的答案: ").append(userAnswer == -1 ? "未回答" :
(userAnswer < question.getOptions().size() ? question.getOptions().get(userAnswer)
: "无效")).append(System.lineSeparator());
builder.append("正确答案: ").append(
question.getOptions().get(question.getCorrectAnswerIndex()))
.append(System.lineSeparator());
builder.append("结果: ").append(isCorrect ? "正确" : "错误").append(System.lineSeparator());
builder.append(System.lineSeparator());
}
String fileName = "exam_result_" + FORMATTER.format(LocalDateTime.now()) + ".txt";
Path outputFile = resultsDirectory.resolve(fileName);
Files.writeString(
outputFile, builder.toString(), StandardCharsets.UTF_8, StandardOpenOption.CREATE_NEW);
return outputFile;
}
private Path getAccountDirectory(String username) {
return Paths.get(BASE_DIRECTORY, username);
}
private Path getQuestionsDirectory(String username) {
return getAccountDirectory(username).resolve(QUESTIONS_SUBDIR);
}
private Path getResultsDirectory(String username) {
return getAccountDirectory(username).resolve(RESULTS_SUBDIR);
}
private void readQuestionsFromFile(Path path, Set<String> questions) {
try {
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
for (String line : lines) {
String trimmed = line.trim();
if (trimmed.isEmpty()) {
continue;
}
int dotIndex = trimmed.indexOf('.');
if (dotIndex >= 0 && dotIndex + 1 < trimmed.length()) {
String question = trimmed.substring(dotIndex + 1).trim();
if (!question.isEmpty()) {
questions.add(question);
}
} else {
questions.add(trimmed);
}
}
} catch (IOException exception) {
System.err.println(
"读取题目文件失败:" + path + ",原因:" + exception.getMessage() + ",将跳过该文件.");
}
}
}

@ -1,18 +1,34 @@
package com.personalproject.auth;
import com.personalproject.model.DifficultyLevel;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
/**
* .
*/
public final class AccountRepository {
private final Map<String, UserAccount> accounts = new HashMap<>();
private final Map<String, String> registrationCodes = new HashMap<>();
private static final Path ACCOUNTS_DIRECTORY = Paths.get("user_data", "accounts");
private static final String FILE_EXTENSION = ".properties";
private final Map<String, UserAccount> accounts = new ConcurrentHashMap<>();
public AccountRepository() {
loadAccounts();
}
/**
* .
@ -25,116 +41,280 @@ public final class AccountRepository {
if (username == null || password == null) {
return Optional.empty();
}
UserAccount account = accounts.get(username.trim());
String normalizedUsername = username.trim();
String normalizedPassword = password.trim();
UserAccount account = accounts.get(normalizedUsername);
if (account == null || !account.isRegistered()) {
return Optional.empty();
}
if (!account.password().equals(password.trim())) {
if (!account.password().equals(hashPassword(normalizedPassword))) {
return Optional.empty();
}
return Optional.of(account);
}
/**
* Registers a new user account with email.
* 使
*
* @param username The username
* @param email The email address
* @param difficultyLevel The selected difficulty level
* @return true if registration was successful, false if username already exists
* @param username
* @param email
* @param difficultyLevel
* @return true false
*/
public boolean registerUser(String username, String email, DifficultyLevel difficultyLevel) {
String trimmedUsername = username.trim();
String trimmedEmail = email.trim();
public synchronized boolean registerUser(String username, String email,
DifficultyLevel difficultyLevel) {
if (username == null || email == null || difficultyLevel == null) {
return false;
}
if (accounts.containsKey(trimmedUsername)) {
return false; // Username already exists
String normalizedUsername = username.trim();
String normalizedEmail = email.trim();
if (normalizedUsername.isEmpty() || normalizedEmail.isEmpty()) {
return false;
}
// Check if email is already used by another account
for (UserAccount account : accounts.values()) {
if (account.email().equals(trimmedEmail) && account.isRegistered()) {
return false; // Email already registered
}
UserAccount existing = accounts.get(normalizedUsername);
if (existing != null && existing.isRegistered()) {
return false;
}
UserAccount newAccount = new UserAccount(
trimmedUsername,
trimmedEmail,
"", // Empty password initially
if (isEmailInUse(normalizedEmail, normalizedUsername)) {
return false;
}
LocalDateTime registrationDate = existing != null ? existing.registrationDate() : LocalDateTime.now();
UserAccount account = new UserAccount(
normalizedUsername,
normalizedEmail,
"",
difficultyLevel,
LocalDateTime.now(),
false); // Not registered until password is set
accounts.put(trimmedUsername, newAccount);
registrationDate,
false);
accounts.put(normalizedUsername, account);
persistAccount(account);
return true;
}
/**
* Sets the password for a user after registration.
*
*
* @param username The username
* @param password The password to set
* @return true if successful, false if user doesn't exist
* @param username
* @param password
* @return true false
*/
public boolean setPassword(String username, String password) {
UserAccount account = accounts.get(username.trim());
if (account == null) {
public synchronized boolean setPassword(String username, String password) {
if (username == null || password == null) {
return false;
}
String normalizedUsername = username.trim();
UserAccount account = accounts.get(normalizedUsername);
if (account == null || account.isRegistered()) {
return false;
}
UserAccount updatedAccount = new UserAccount(
account.username(),
account.email(),
password,
hashPassword(password.trim()),
account.difficultyLevel(),
account.registrationDate(),
true); // Now registered
accounts.put(username.trim(), updatedAccount);
true);
accounts.put(normalizedUsername, updatedAccount);
persistAccount(updatedAccount);
return true;
}
/**
* Changes the password for an existing user.
*
*
* @param username The username
* @param oldPassword The current password
* @param newPassword The new password
* @return true if successful, false if old password is incorrect or user doesn't exist
* @param username
* @param oldPassword
* @param newPassword
* @return true false
*/
public boolean changePassword(String username, String oldPassword, String newPassword) {
UserAccount account = accounts.get(username.trim());
if (account == null || !account.password().equals(oldPassword) || !account.isRegistered()) {
public synchronized boolean changePassword(String username, String oldPassword,
String newPassword) {
if (username == null || oldPassword == null || newPassword == null) {
return false;
}
String normalizedUsername = username.trim();
UserAccount account = accounts.get(normalizedUsername);
if (account == null || !account.isRegistered()) {
return false;
}
if (!account.password().equals(hashPassword(oldPassword.trim()))) {
return false;
}
UserAccount updatedAccount = new UserAccount(
account.username(),
account.email(),
newPassword,
hashPassword(newPassword.trim()),
account.difficultyLevel(),
account.registrationDate(),
true);
accounts.put(username.trim(), updatedAccount);
accounts.put(normalizedUsername, updatedAccount);
persistAccount(updatedAccount);
return true;
}
/**
* Checks if a user exists in the system.
* 便
*
* @param username
*/
public synchronized void removeUnverifiedUser(String username) {
if (username == null) {
return;
}
String normalizedUsername = username.trim();
UserAccount account = accounts.get(normalizedUsername);
if (account != null && !account.isRegistered()) {
accounts.remove(normalizedUsername);
deleteAccountFile(normalizedUsername);
}
}
/**
*
*
* @param username The username to check
* @return true if user exists, false otherwise
* @param username
* @return true false
*/
public boolean userExists(String username) {
if (username == null) {
return false;
}
return accounts.containsKey(username.trim());
}
/**
* Gets a user account by username.
*
*
* @param username The username
* @return Optional containing the user account if found
* @param username
* @return Optional
*/
public Optional<UserAccount> getUser(String username) {
if (username == null) {
return Optional.empty();
}
return Optional.ofNullable(accounts.get(username.trim()));
}
private void loadAccounts() {
try {
if (!Files.exists(ACCOUNTS_DIRECTORY)) {
Files.createDirectories(ACCOUNTS_DIRECTORY);
return;
}
try (var paths = Files.list(ACCOUNTS_DIRECTORY)) {
paths
.filter(path -> path.getFileName().toString().endsWith(FILE_EXTENSION))
.forEach(this::loadAccountFromFile);
}
} catch (IOException exception) {
throw new IllegalStateException("加载账户数据失败", exception);
}
}
private void loadAccountFromFile(Path file) {
Properties properties = new Properties();
try (Reader reader = Files.newBufferedReader(file, StandardCharsets.UTF_8)) {
properties.load(reader);
} catch (IOException exception) {
System.err.println("读取账户文件失败: " + file + ",原因: " + exception.getMessage());
return;
}
String username = properties.getProperty("username");
if (username == null || username.isBlank()) {
return;
}
String email = properties.getProperty("email", "");
String passwordHash = properties.getProperty("passwordHash", "");
String difficultyValue = properties.getProperty("difficulty", DifficultyLevel.PRIMARY.name());
String registrationDateValue = properties.getProperty("registrationDate");
String registeredValue = properties.getProperty("registered", "false");
try {
DifficultyLevel difficultyLevel = DifficultyLevel.valueOf(difficultyValue);
LocalDateTime registrationDate = registrationDateValue == null
? LocalDateTime.now()
: LocalDateTime.parse(registrationDateValue);
boolean registered = Boolean.parseBoolean(registeredValue);
UserAccount account = new UserAccount(
username,
email,
passwordHash,
difficultyLevel,
registrationDate,
registered);
accounts.put(username, account);
} catch (Exception exception) {
System.err.println("解析账户文件失败: " + file + ",原因: " + exception.getMessage());
}
}
private void persistAccount(UserAccount account) {
Properties properties = new Properties();
properties.setProperty("username", account.username());
properties.setProperty("email", account.email());
properties.setProperty("passwordHash", account.password());
properties.setProperty("difficulty", account.difficultyLevel().name());
properties.setProperty("registrationDate", account.registrationDate().toString());
properties.setProperty("registered", Boolean.toString(account.isRegistered()));
Path targetFile = accountFile(account.username());
try {
if (!Files.exists(ACCOUNTS_DIRECTORY)) {
Files.createDirectories(ACCOUNTS_DIRECTORY);
}
try (Writer writer = Files.newBufferedWriter(targetFile, StandardCharsets.UTF_8)) {
properties.store(writer, "User account data");
}
} catch (IOException exception) {
throw new IllegalStateException("保存账户数据失败: " + account.username(), exception);
}
}
private void deleteAccountFile(String username) {
Path file = accountFile(username);
try {
Files.deleteIfExists(file);
} catch (IOException exception) {
System.err.println("删除账户文件失败: " + file + ",原因: " + exception.getMessage());
}
}
private boolean isEmailInUse(String email, String currentUsername) {
return accounts.values().stream()
.anyMatch(account -> account.email().equalsIgnoreCase(email)
&& !account.username().equals(currentUsername));
}
private Path accountFile(String username) {
return ACCOUNTS_DIRECTORY.resolve(username + FILE_EXTENSION);
}
private String hashPassword(String password) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hashBytes = digest.digest(password.getBytes(StandardCharsets.UTF_8));
return toHex(hashBytes);
} catch (NoSuchAlgorithmException exception) {
throw new IllegalStateException("当前运行环境不支持SHA-256算法", exception);
}
}
private String toHex(byte[] bytes) {
StringBuilder builder = new StringBuilder(bytes.length * 2);
for (byte value : bytes) {
builder.append(String.format("%02x", value));
}
return builder.toString();
}
}

@ -1,24 +1,54 @@
package com.personalproject.auth;
import jakarta.mail.Authenticator;
import jakarta.mail.Message;
import jakarta.mail.MessagingException;
import jakarta.mail.PasswordAuthentication;
import jakarta.mail.Session;
import jakarta.mail.Transport;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;
/**
* Interface for sending emails with registration codes.
*
*/
public final class EmailService {
private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
private static final int CODE_LENGTH = 6;
private static final Random RANDOM = new Random();
private static final Path OUTBOX_DIRECTORY = Paths.get("user_data", "emails");
private static final String CONFIG_RESOURCE = "email-config.properties";
private static final DateTimeFormatter DATE_TIME_FORMATTER =
DateTimeFormatter.ofPattern("yyyyMMdd-HHmmss");
private static final Map<String, String> LAST_CODES = new ConcurrentHashMap<>();
private static final AtomicReference<MailConfiguration> CONFIG_CACHE = new AtomicReference<>();
private static final String DEFAULT_SUBJECT = "数学学习软件注册验证码";
private EmailService() {
// Prevent instantiation of utility class
// 防止实例化此工具类
}
/**
* Generates a random registration code.
*
*
* @return A randomly generated registration code
* @return
*/
public static String generateRegistrationCode() {
StringBuilder code = new StringBuilder();
@ -29,34 +59,172 @@ public final class EmailService {
}
/**
* Sends a registration code to the specified email address. In a real implementation, this would
* connect to an email server.
*
*
* @param email The email address to send the code to
* @param registrationCode The registration code to send
* @return true if successfully sent (in this mock implementation, always true)
* @param email
* @param registrationCode
* @return true
*/
public static boolean sendRegistrationCode(String email, String registrationCode) {
// In a real implementation, this would connect to an email server
// For the mock implementation, we'll just print to console
System.out.println("Sending registration code " + registrationCode + " to " + email);
return true;
try {
MailConfiguration configuration = loadConfiguration();
sendEmail(email, registrationCode, configuration);
persistMessage(email, registrationCode);
LAST_CODES.put(email.trim().toLowerCase(), registrationCode);
return true;
} catch (Exception exception) {
System.err.println("发送验证码失败: " + exception.getMessage());
return false;
}
}
/**
* Validates if an email address has a valid format.
* 便
*
* @param email The email address to validate
* @return true if the email has valid format, false otherwise
* @param email
* @return
*/
public static Optional<String> getLastSentRegistrationCode(String email) {
if (email == null) {
return Optional.empty();
}
return Optional.ofNullable(LAST_CODES.get(email.trim().toLowerCase()));
}
/**
*
*
* @param email
* @return true false
*/
public static boolean isValidEmail(String email) {
if (email == null || email.trim().isEmpty()) {
return false;
}
// Simple email validation using regex
String emailRegex = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@"
+ "(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";
return email.matches(emailRegex);
}
}
private static MailConfiguration loadConfiguration() throws IOException {
MailConfiguration cached = CONFIG_CACHE.get();
if (cached != null) {
return cached;
}
synchronized (CONFIG_CACHE) {
cached = CONFIG_CACHE.get();
if (cached != null) {
return cached;
}
Properties properties = new Properties();
try (InputStream inputStream =
EmailService.class.getClassLoader().getResourceAsStream(CONFIG_RESOURCE)) {
if (inputStream == null) {
throw new IllegalStateException(
"类路径下缺少邮箱配置文件: " + CONFIG_RESOURCE
+ ",请在 src/main/resources 下提供该文件");
}
try (InputStreamReader reader =
new InputStreamReader(inputStream, StandardCharsets.UTF_8)) {
properties.load(reader);
}
}
String username = require(properties, "mail.username");
String password = require(properties, "mail.password");
String from = properties.getProperty("mail.from", username);
String subject = properties.getProperty("mail.subject", DEFAULT_SUBJECT);
Properties smtpProperties = new Properties();
for (Map.Entry<Object, Object> entry : properties.entrySet()) {
String key = entry.getKey().toString();
if (key.startsWith("mail.smtp.")) {
smtpProperties.put(key, entry.getValue());
}
}
if (!smtpProperties.containsKey("mail.smtp.host")) {
throw new IllegalStateException("邮箱配置缺少 mail.smtp.host");
}
if (!smtpProperties.containsKey("mail.smtp.port")) {
throw new IllegalStateException("邮箱配置缺少 mail.smtp.port");
}
smtpProperties.putIfAbsent("mail.smtp.auth", "true");
smtpProperties.putIfAbsent("mail.smtp.starttls.enable", "true");
MailConfiguration configuration =
new MailConfiguration(smtpProperties, username, password, from, subject);
CONFIG_CACHE.set(configuration);
return configuration;
}
}
private static void sendEmail(
String recipientEmail, String registrationCode, MailConfiguration configuration)
throws MessagingException {
Session session = Session.getInstance(configuration.smtpProperties(), new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(configuration.username(), configuration.password());
}
});
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(configuration.from()));
message.setRecipients(
Message.RecipientType.TO,
InternetAddress.parse(recipientEmail, false));
message.setSubject(configuration.subject());
String body = "您好,您的注册码为:" + registrationCode + System.lineSeparator()
+ "请在10分钟内使用该验证码完成注册。";
message.setText(body, StandardCharsets.UTF_8.name());
Transport.send(message);
}
private static void persistMessage(String email, String registrationCode) throws IOException {
if (!Files.exists(OUTBOX_DIRECTORY)) {
Files.createDirectories(OUTBOX_DIRECTORY);
}
String sanitizedEmail = sanitizeEmail(email);
String timestamp = DATE_TIME_FORMATTER.format(LocalDateTime.now());
Path messageFile = OUTBOX_DIRECTORY.resolve(sanitizedEmail + "_" + timestamp + ".txt");
StringBuilder content = new StringBuilder();
content.append("收件人: ").append(email).append(System.lineSeparator());
content.append("注册码: ").append(registrationCode).append(System.lineSeparator());
content.append("发送时间: ").append(LocalDateTime.now()).append(System.lineSeparator());
Files.writeString(
messageFile,
content.toString(),
StandardCharsets.UTF_8,
StandardOpenOption.CREATE_NEW,
StandardOpenOption.WRITE);
}
private static String require(Properties properties, String key) {
String value = properties.getProperty(key);
if (value == null || value.trim().isEmpty()) {
throw new IllegalStateException("邮箱配置缺少必要字段: " + key);
}
return value.trim();
}
private static String sanitizeEmail(String email) {
return email.replaceAll("[^a-zA-Z0-9._-]", "_");
}
private record MailConfiguration(
Properties smtpProperties,
String username,
String password,
String from,
String subject) {
}
}

@ -3,7 +3,7 @@ package com.personalproject.auth;
import java.util.regex.Pattern;
/**
* Utility class for password validation.
*
*/
public final class PasswordValidator {
@ -11,20 +11,27 @@ public final class PasswordValidator {
Pattern.compile("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)[a-zA-Z\\d]{6,10}$");
private PasswordValidator() {
// Prevent instantiation of utility class
// 防止实例化此工具类
}
/**
* Validates if a password meets the requirements: - 6-10 characters - Contains at least one
* uppercase letter - Contains at least one lowercase letter - Contains at least one digit.
*
* - 6-10
* -
* -
* -
*
* @param password The password to validate
* @return true if password meets requirements, false otherwise
* @param password
* @return true false
*/
public static boolean isValidPassword(String password) {
if (password == null) {
return false;
}
return PASSWORD_PATTERN.matcher(password).matches();
String normalized = password.trim();
if (normalized.isEmpty()) {
return false;
}
return PASSWORD_PATTERN.matcher(normalized).matches();
}
}
}

@ -15,13 +15,13 @@ public record UserAccount(
boolean isRegistered) {
/**
* Creates a new user account with registration date set to now.
* 使
*
* @param username The username
* @param email The email address
* @param password The password
* @param difficultyLevel The selected difficulty level
* @param isRegistered Whether the user has completed registration
* @param username
* @param email
* @param password
* @param difficultyLevel
* @param isRegistered
*/
public UserAccount {
if (username == null || username.trim().isEmpty()) {

@ -144,12 +144,12 @@ public final class MathLearningController {
}
/**
* Gets a user account by username.
*
*
* @param username The username
* @return Optional containing the user account if found
* @param username
* @return Optional
*/
public Optional<com.personalproject.auth.UserAccount> getUserAccount(String username) {
return mathLearningService.getUser(username);
}
}
}

@ -5,8 +5,10 @@ import com.personalproject.service.MathExpressionEvaluator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
/**
* .
@ -59,22 +61,18 @@ public final class PrimaryQuestionGenerator implements QuestionGenerator, QuizQu
try {
correctAnswer = MathExpressionEvaluator.evaluate(expression);
} catch (Exception e) {
// Fallback if evaluation fails
// 如果计算失败则使用兜底值
correctAnswer = 0.0;
}
// 生成选项
List<String> options = generateOptions(correctAnswer, random);
// 随机选择正确答案索引
int correctAnswerIndex = random.nextInt(options.size());
// 确保正确答案在选项中
String correctOption = String.format("%.2f", correctAnswer);
String oldOption = options.set(correctAnswerIndex, correctOption);
// Add the displaced option back to maintain 4 options
options.add(oldOption);
String correctOption = formatOption(correctAnswer);
int correctAnswerIndex = options.indexOf(correctOption);
if (correctAnswerIndex < 0) {
// 兜底逻辑:确保正确答案存在于选项中
options.set(0, correctOption);
correctAnswerIndex = 0;
}
return new QuizQuestion(expression, options, correctAnswerIndex);
}
@ -83,27 +81,40 @@ public final class PrimaryQuestionGenerator implements QuestionGenerator, QuizQu
*
*/
private List<String> generateOptions(double correctAnswer, Random random) {
List<String> options = new ArrayList<>();
// Add correct answer as one of the options
options.add(String.format("%.2f", correctAnswer));
String correctOption = formatOption(correctAnswer);
Set<String> optionSet = new LinkedHashSet<>();
optionSet.add(correctOption);
// Add incorrect options
for (int i = 0; i < OPTIONS_COUNT - 1; i++) {
double incorrectAnswer = correctAnswer + (random.nextGaussian() * 10); // Add random offset
if (Math.abs(incorrectAnswer - correctAnswer) < 0.1) { // Ensure different
incorrectAnswer += 1.5;
double scale = Math.max(Math.abs(correctAnswer) * 0.2, 1.0);
int attempts = 0;
while (optionSet.size() < OPTIONS_COUNT && attempts < 100) {
double delta = random.nextGaussian() * scale;
if (Math.abs(delta) < 0.5) {
double direction = random.nextBoolean() ? 1 : -1;
delta = direction * (0.5 + random.nextDouble()) * scale;
}
double candidate = correctAnswer + delta;
if (Double.isNaN(candidate) || Double.isInfinite(candidate)) {
attempts++;
continue;
}
options.add(String.format("%.2f", incorrectAnswer));
optionSet.add(formatOption(candidate));
attempts++;
}
// Shuffle to randomize correct answer position
double step = Math.max(scale, 1.0);
while (optionSet.size() < OPTIONS_COUNT) {
double candidate = correctAnswer + step * optionSet.size();
optionSet.add(formatOption(candidate));
step += 1.0;
}
List<String> options = new ArrayList<>(optionSet);
Collections.shuffle(options, random);
// Find the correct answer index after shuffling
String correctAnswerStr = String.format("%.2f", correctAnswer);
int correctIndex = options.indexOf(correctAnswerStr);
return options;
}
private String formatOption(double value) {
return String.format("%.2f", value);
}
}

@ -2,10 +2,11 @@ package com.personalproject.model;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Represents an exam session for a user.
*
*/
public final class ExamSession {
@ -17,11 +18,11 @@ public final class ExamSession {
private int currentQuestionIndex;
/**
* Creates a new exam session.
*
*
* @param username The username of the test taker
* @param difficultyLevel The difficulty level of the exam
* @param questions The list of questions for the exam
* @param username
* @param difficultyLevel
* @param questions
*/
public ExamSession(String username, DifficultyLevel difficultyLevel,
List<QuizQuestion> questions) {
@ -37,80 +38,77 @@ public final class ExamSession {
this.username = username;
this.difficultyLevel = difficultyLevel;
this.questions = List.copyOf(questions); // Immutable copy of questions
this.userAnswers = new ArrayList<>();
// Initialize user answers with -1 (no answer selected)
for (int i = 0; i < questions.size(); i++) {
userAnswers.add(-1);
}
this.questions = List.copyOf(questions); // 题目的不可变副本
this.userAnswers = new ArrayList<>(Collections.nCopies(questions.size(), -1));
this.startTime = LocalDateTime.now();
this.currentQuestionIndex = 0;
}
/**
* Gets the username of the test taker.
*
*
* @return The username
* @return
*/
public String getUsername() {
return username;
}
/**
* Gets the difficulty level of the exam.
*
*
* @return The difficulty level
* @return
*/
public DifficultyLevel getDifficultyLevel() {
return difficultyLevel;
}
/**
* Gets the list of questions in the exam.
*
*
* @return An unmodifiable list of questions
* @return
*/
public List<QuizQuestion> getQuestions() {
return questions;
}
/**
* Gets the user's answers to the questions.
*
*
* @return A list of answer indices (-1 means no answer selected)
* @return -1
*/
public List<Integer> getUserAnswers() {
return List.copyOf(userAnswers); // Return a copy to prevent modification
return List.copyOf(userAnswers); // 返回副本以防止被修改
}
/**
* Gets the current question index.
*
*
* @return The current question index
* @return
*/
public int getCurrentQuestionIndex() {
return currentQuestionIndex;
}
/**
* Sets the user's answer for the current question.
*
*
* @param answerIndex The index of the selected answer
* @param answerIndex
*/
public void setAnswer(int answerIndex) {
if (currentQuestionIndex < 0 || currentQuestionIndex >= questions.size()) {
throw new IllegalStateException("No valid question at current index");
}
if (answerIndex < 0 || answerIndex > questions.get(currentQuestionIndex).getOptions().size()) {
int optionCount = questions.get(currentQuestionIndex).getOptions().size();
if (answerIndex < 0 || answerIndex >= optionCount) {
throw new IllegalArgumentException("Invalid answer index");
}
userAnswers.set(currentQuestionIndex, answerIndex);
}
/**
* Moves to the next question.
*
*
* @return true if successfully moved to next question, false if already at the last question
* @return true false
*/
public boolean goToNextQuestion() {
if (currentQuestionIndex < questions.size() - 1) {
@ -121,9 +119,9 @@ public final class ExamSession {
}
/**
* Moves to the previous question.
*
*
* @return true if successfully moved to previous question, false if already at the first question
* @return true false
*/
public boolean goToPreviousQuestion() {
if (currentQuestionIndex > 0) {
@ -134,18 +132,18 @@ public final class ExamSession {
}
/**
* Checks if the exam is complete (all questions answered or at the end).
*
*
* @return true if the exam is complete, false otherwise
* @return true false
*/
public boolean isComplete() {
return currentQuestionIndex >= questions.size() - 1;
return userAnswers.stream().allMatch(answer -> answer != -1);
}
/**
* Gets the current question.
*
*
* @return The current quiz question
* @return
*/
public QuizQuestion getCurrentQuestion() {
if (currentQuestionIndex < 0 || currentQuestionIndex >= questions.size()) {
@ -155,10 +153,10 @@ public final class ExamSession {
}
/**
* Gets the user's answer for a specific question.
*
*
* @param questionIndex The index of the question
* @return The index of the user's answer (or -1 if no answer selected)
* @param questionIndex
* @return -1
*/
public int getUserAnswer(int questionIndex) {
if (questionIndex < 0 || questionIndex >= questions.size()) {
@ -168,9 +166,9 @@ public final class ExamSession {
}
/**
* Calculates the score as a percentage.
*
*
* @return The score as a percentage (0-100)
* @return 0-100
*/
public double calculateScore() {
int correctCount = 0;
@ -185,19 +183,19 @@ public final class ExamSession {
}
/**
* Gets the total number of questions in the exam.
*
*
* @return The total number of questions
* @return
*/
public int getTotalQuestions() {
return questions.size();
}
/**
* Checks if a specific question has been answered.
*
*
* @param questionIndex The index of the question
* @return true if the question has been answered, false otherwise
* @param questionIndex
* @return true false
*/
public boolean hasAnswered(int questionIndex) {
if (questionIndex < 0 || questionIndex >= questions.size()) {
@ -207,18 +205,18 @@ public final class ExamSession {
}
/**
* Gets the start time of the exam.
*
*
* @return The start time
* @return
*/
public LocalDateTime getStartTime() {
return startTime;
}
/**
* Gets the number of correct answers.
*
*
* @return The count of correct answers
* @return
*/
public int getCorrectAnswersCount() {
int correctCount = 0;
@ -233,9 +231,9 @@ public final class ExamSession {
}
/**
* Gets the number of incorrect answers.
*
*
* @return The count of incorrect answers
* @return
*/
public int getIncorrectAnswersCount() {
int totalAnswered = 0;
@ -254,4 +252,4 @@ public final class ExamSession {
return totalAnswered - correctCount;
}
}
}

@ -3,7 +3,7 @@ package com.personalproject.model;
import java.util.List;
/**
* Represents a quiz question with multiple choice options.
*
*/
public final class QuizQuestion {
@ -12,11 +12,11 @@ public final class QuizQuestion {
private final int correctAnswerIndex;
/**
* Creates a new quiz question.
*
*
* @param questionText The text of the question
* @param options The list of answer options
* @param correctAnswerIndex The index of the correct answer in the options list
* @param questionText
* @param options
* @param correctAnswerIndex
*/
public QuizQuestion(String questionText, List<String> options, int correctAnswerIndex) {
if (questionText == null || questionText.trim().isEmpty()) {
@ -30,44 +30,44 @@ public final class QuizQuestion {
}
this.questionText = questionText;
this.options = List.copyOf(options); // Immutable copy
this.options = List.copyOf(options); // 不可变副本
this.correctAnswerIndex = correctAnswerIndex;
}
/**
* Gets the question text.
*
*
* @return The question text
* @return
*/
public String getQuestionText() {
return questionText;
}
/**
* Gets the list of answer options.
*
*
* @return An unmodifiable list of answer options
* @return
*/
public List<String> getOptions() {
return options;
}
/**
* Gets the index of the correct answer in the options list.
*
*
* @return The index of the correct answer
* @return
*/
public int getCorrectAnswerIndex() {
return correctAnswerIndex;
}
/**
* Checks if the given answer index matches the correct answer.
*
*
* @param answerIndex The index of the user's answer
* @return true if the answer is correct, false otherwise
* @param answerIndex
* @return true false
*/
public boolean isAnswerCorrect(int answerIndex) {
return answerIndex == correctAnswerIndex;
}
}
}

@ -4,11 +4,16 @@ import com.personalproject.generator.QuestionGenerator;
import com.personalproject.model.DifficultyLevel;
import com.personalproject.model.ExamSession;
import com.personalproject.model.QuizQuestion;
import com.personalproject.storage.QuestionStorageService;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
/**
* .
@ -19,19 +24,23 @@ public final class ExamService {
private final Map<DifficultyLevel, QuestionGenerator> generators;
private final Random random = new Random();
private final QuestionGenerationService questionGenerationService;
private final QuestionStorageService questionStorageService;
/**
* .
*
* @param generatorMap
* @param questionGenerationService
* @param questionStorageService
*/
public ExamService(
Map<DifficultyLevel, QuestionGenerator> generatorMap,
QuestionGenerationService questionGenerationService) {
QuestionGenerationService questionGenerationService,
QuestionStorageService questionStorageService) {
this.generators = new EnumMap<>(DifficultyLevel.class);
this.generators.putAll(generatorMap);
this.questionGenerationService = questionGenerationService;
this.questionStorageService = questionStorageService;
}
/**
@ -49,27 +58,25 @@ public final class ExamService {
}
// 根据难度级别生成题目
List<String> generatedQuestions = new ArrayList<>();
QuestionGenerator generator = generators.get(difficultyLevel);
if (generator == null) {
if (!generators.containsKey(difficultyLevel)) {
throw new IllegalArgumentException("找不到难度级别的生成器: " + difficultyLevel);
}
for (int i = 0; i < questionCount; i++) {
String question = generator.generateQuestion(random);
generatedQuestions.add(question);
}
try {
Set<String> existingQuestions = questionStorageService.loadExistingQuestions(username);
List<String> uniqueQuestions = questionGenerationService.generateUniqueQuestions(
difficultyLevel, questionCount, existingQuestions);
// 将字符串题目转换为带有选项和答案的QuizQuestion对象
List<QuizQuestion> quizQuestions = new ArrayList<>();
for (String questionText : generatedQuestions) {
List<String> options = generateOptions(questionText);
int correctAnswerIndex = generateCorrectAnswerIndex(options.size());
QuizQuestion quizQuestion = new QuizQuestion(questionText, options, correctAnswerIndex);
quizQuestions.add(quizQuestion);
}
List<QuizQuestion> quizQuestions = new ArrayList<>();
for (String questionText : uniqueQuestions) {
quizQuestions.add(buildQuizQuestion(questionText));
}
return new ExamSession(username, difficultyLevel, quizQuestions);
questionStorageService.saveQuestions(username, uniqueQuestions);
return new ExamSession(username, difficultyLevel, quizQuestions);
} catch (IOException exception) {
throw new IllegalStateException("生成考试题目失败", exception);
}
}
/**
@ -88,53 +95,64 @@ public final class ExamService {
return new ExamSession(username, difficultyLevel, questions);
}
/**
* . - .
*
* @param questionText
* @return
*/
private List<String> generateOptions(String questionText) {
List<String> options = new ArrayList<>();
// 为每个题目生成4个选项
private QuizQuestion buildQuizQuestion(String questionText) {
try {
// 尝试将数学表达式作为正确答案进行评估
double correctAnswer = MathExpressionEvaluator.evaluate(questionText);
String formattedCorrectAnswer = formatAnswer(correctAnswer);
List<String> options = buildOptions(correctAnswer, formattedCorrectAnswer);
int correctAnswerIndex = options.indexOf(formattedCorrectAnswer);
if (correctAnswerIndex < 0) {
options.set(0, formattedCorrectAnswer);
correctAnswerIndex = 0;
}
return new QuizQuestion(questionText, options, correctAnswerIndex);
} catch (RuntimeException exception) {
List<String> fallbackOptions = new ArrayList<>();
for (int i = 1; i <= OPTIONS_COUNT; i++) {
fallbackOptions.add("选项" + i);
}
return new QuizQuestion(questionText, fallbackOptions, 0);
}
}
// 创建正确答案选项
options.add(String.format("%.2f", correctAnswer));
// 生成3个错误选项
for (int i = 0; i < OPTIONS_COUNT - 1; i++) {
double incorrectAnswer = correctAnswer + (random.nextGaussian() * 10); // 添加一些随机偏移
if (Math.abs(incorrectAnswer - correctAnswer) < 0.1) { // 确保不同
incorrectAnswer += 1.5;
}
options.add(String.format("%.2f", incorrectAnswer));
private List<String> buildOptions(double correctAnswer, String formattedCorrectAnswer) {
Set<String> optionSet = new LinkedHashSet<>();
optionSet.add(formattedCorrectAnswer);
int attempts = 0;
while (optionSet.size() < OPTIONS_COUNT && attempts < 100) {
double offset = generateOffset(correctAnswer);
double candidateValue = correctAnswer + offset;
if (Double.isNaN(candidateValue) || Double.isInfinite(candidateValue)) {
attempts++;
continue;
}
} catch (Exception e) {
// 如果评估失败,创建虚拟选项
for (int i = 0; i < OPTIONS_COUNT; i++) {
options.add("选项 " + (i + 1));
String candidate = formatAnswer(candidateValue);
if (!candidate.equals(formattedCorrectAnswer)) {
optionSet.add(candidate);
}
attempts++;
}
// 随机打乱选项以随机化正确答案的位置
java.util.Collections.shuffle(options, random);
while (optionSet.size() < OPTIONS_COUNT) {
optionSet.add(formatAnswer(correctAnswer + optionSet.size() * 1.5));
}
// 找到打乱后的正确答案索引
// 对于此模拟实现,我们将返回第一个选项(索引0)作为正确答案
// 实际实现将跟踪正确答案
List<String> options = new ArrayList<>(optionSet);
Collections.shuffle(options, random);
return options;
}
/**
* .
*
* @param optionCount
* @return 0optionCount-1
*/
private int generateCorrectAnswerIndex(int optionCount) {
return random.nextInt(optionCount);
private double generateOffset(double base) {
double scale = Math.max(1.0, Math.abs(base) / 2.0);
double offset = random.nextGaussian() * scale;
if (Math.abs(offset) < 0.5) {
offset += offset >= 0 ? 1.5 : -1.5;
}
return offset;
}
private String formatAnswer(double value) {
return String.format("%.2f", value);
}
}
}

@ -3,15 +3,17 @@ package com.personalproject.service;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
import java.util.function.DoubleUnaryOperator;
import java.util.regex.Pattern;
/**
* A mathematical expression evaluator that can handle basic arithmetic operations.
*
*/
public final class MathExpressionEvaluator {
private static final Pattern NUMBER_PATTERN = Pattern.compile("-?\\d+(\\.\\d+)?");
private static final Map<Character, Integer> PRECEDENCE = new HashMap<>();
private static final Map<String, DoubleUnaryOperator> FUNCTIONS = new HashMap<>();
static {
PRECEDENCE.put('+', 1);
@ -19,44 +21,49 @@ public final class MathExpressionEvaluator {
PRECEDENCE.put('*', 2);
PRECEDENCE.put('/', 2);
PRECEDENCE.put('^', 3);
FUNCTIONS.put("sin", angle -> Math.sin(Math.toRadians(angle)));
FUNCTIONS.put("cos", angle -> Math.cos(Math.toRadians(angle)));
FUNCTIONS.put("tan", angle -> Math.tan(Math.toRadians(angle)));
FUNCTIONS.put("sqrt", Math::sqrt);
}
private MathExpressionEvaluator() {
// Prevent instantiation of utility class
// 防止实例化此工具类
}
/**
* Evaluates a mathematical expression string.
*
*
* @param expression The mathematical expression to evaluate
* @return The result of the evaluation
* @throws IllegalArgumentException If the expression is invalid
* @param expression
* @return
* @throws IllegalArgumentException
*/
public static double evaluate(String expression) {
if (expression == null) {
throw new IllegalArgumentException("Expression cannot be null");
}
expression = expression.replaceAll("\\s+", ""); // Remove whitespace
expression = expression.replaceAll("\\s+", ""); // 移除空白字符
if (expression.isEmpty()) {
throw new IllegalArgumentException("Expression cannot be empty");
}
// Tokenize the expression
// 将表达式拆分为记号
String[] tokens = tokenize(expression);
// Convert infix to postfix notation using Shunting Yard algorithm
// 使用调度场算法将中缀表达式转换为后缀表达式
String[] postfix = infixToPostfix(tokens);
// Evaluate the postfix expression
// 计算后缀表达式
return evaluatePostfix(postfix);
}
/**
* Tokenizes the expression into numbers and operators.
*
*
* @param expression The expression to tokenize
* @return An array of tokens
* @param expression
* @return
*/
private static String[] tokenize(String expression) {
java.util.List<String> tokens = new java.util.ArrayList<>();
@ -67,6 +74,21 @@ public final class MathExpressionEvaluator {
if (Character.isDigit(c) || c == '.') {
currentNumber.append(c);
} else if (Character.isLetter(c)) {
if (currentNumber.length() > 0) {
tokens.add(currentNumber.toString());
currentNumber.setLength(0);
}
StringBuilder functionBuilder = new StringBuilder();
functionBuilder.append(c);
while (i + 1 < expression.length() && Character.isLetter(expression.charAt(i + 1))) {
functionBuilder.append(expression.charAt(++i));
}
String function = functionBuilder.toString();
if (!isFunction(function)) {
throw new IllegalArgumentException("Unsupported function: " + function);
}
tokens.add(function);
} else if (c == '(' || c == ')') {
if (currentNumber.length() > 0) {
tokens.add(currentNumber.toString());
@ -79,7 +101,7 @@ public final class MathExpressionEvaluator {
currentNumber.setLength(0);
}
// Handle unary minus
// 处理一元负号
if (c == '-' && (i == 0 || expression.charAt(i - 1) == '(')) {
currentNumber.append(c);
} else {
@ -98,20 +120,24 @@ public final class MathExpressionEvaluator {
}
/**
* Checks if the character is an operator.
*
*
* @param c The character to check
* @return true if the character is an operator, false otherwise
* @param c
* @return true false
*/
private static boolean isOperator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/' || c == '^';
}
private static boolean isFunction(String token) {
return FUNCTIONS.containsKey(token);
}
/**
* Converts infix notation to postfix notation using the Shunting Yard algorithm.
* 使
*
* @param tokens The tokens in infix notation
* @return An array of tokens in postfix notation
* @param tokens
* @return
*/
private static String[] infixToPostfix(String[] tokens) {
java.util.List<String> output = new java.util.ArrayList<>();
@ -120,6 +146,8 @@ public final class MathExpressionEvaluator {
for (String token : tokens) {
if (isNumber(token)) {
output.add(token);
} else if (isFunction(token)) {
operators.push(token);
} else if (token.equals("(")) {
operators.push(token);
} else if (token.equals(")")) {
@ -127,7 +155,10 @@ public final class MathExpressionEvaluator {
output.add(operators.pop());
}
if (!operators.isEmpty()) {
operators.pop(); // Remove the "("
operators.pop(); // 移除 "("
}
if (!operators.isEmpty() && isFunction(operators.peek())) {
output.add(operators.pop());
}
} else if (isOperator(token.charAt(0))) {
while (!operators.isEmpty()
@ -140,17 +171,21 @@ public final class MathExpressionEvaluator {
}
while (!operators.isEmpty()) {
output.add(operators.pop());
String operator = operators.pop();
if (operator.equals("(") || operator.equals(")")) {
throw new IllegalArgumentException("Mismatched parentheses in expression");
}
output.add(operator);
}
return output.toArray(new String[0]);
}
/**
* Evaluates a postfix expression.
*
*
* @param postfix The tokens in postfix notation
* @return The result of the evaluation
* @param postfix
* @return
*/
private static double evaluatePostfix(String[] postfix) {
Stack<Double> values = new Stack<>();
@ -167,6 +202,14 @@ public final class MathExpressionEvaluator {
double a = values.pop();
double result = performOperation(a, b, token.charAt(0));
values.push(result);
} else if (isFunction(token)) {
if (values.isEmpty()) {
throw new IllegalArgumentException("Invalid expression: insufficient operands for function");
}
double value = values.pop();
values.push(applyFunction(token, value));
} else {
throw new IllegalArgumentException("Unknown token: " + token);
}
}
@ -178,12 +221,12 @@ public final class MathExpressionEvaluator {
}
/**
* Performs the specified operation on the two operands.
*
*
* @param a The first operand
* @param b The second operand
* @param operator The operator to apply
* @return The result of the operation
* @param a
* @param b
* @param operator
* @return
*/
private static double performOperation(double a, double b, char operator) {
switch (operator) {
@ -205,13 +248,21 @@ public final class MathExpressionEvaluator {
}
}
private static double applyFunction(String function, double value) {
DoubleUnaryOperator operator = FUNCTIONS.get(function);
if (operator == null) {
throw new IllegalArgumentException("Unknown function: " + function);
}
return operator.applyAsDouble(value);
}
/**
* Checks if the token is a number.
*
*
* @param token The token to check
* @return true if the token is a number, false otherwise
* @param token
* @return true false
*/
private static boolean isNumber(String token) {
return NUMBER_PATTERN.matcher(token).matches();
}
}
}

@ -30,10 +30,10 @@ public final class MathLearningService {
public MathLearningService(
Map<DifficultyLevel, QuestionGenerator> generatorMap,
QuestionGenerationService questionGenerationService) {
this.storageService = new QuestionStorageService();
this.accountRepository = new AccountRepository();
this.registrationService = new RegistrationService(accountRepository);
this.examService = new ExamService(generatorMap, questionGenerationService);
this.storageService = new QuestionStorageService();
this.examService = new ExamService(generatorMap, questionGenerationService, storageService);
this.resultService = new ExamResultService();
}
@ -169,12 +169,12 @@ public final class MathLearningService {
}
/**
* Gets a user account by username.
*
*
* @param username The username
* @return Optional containing the user account if found
* @param username
* @return Optional
*/
public Optional<com.personalproject.auth.UserAccount> getUser(String username) {
return registrationService.getUser(username);
}
}
}

@ -6,6 +6,7 @@ import com.personalproject.auth.PasswordValidator;
import com.personalproject.model.DifficultyLevel;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/**
@ -16,6 +17,7 @@ public final class RegistrationService {
private final AccountRepository accountRepository;
private final Map<String, String> pendingRegistrations;
private final Map<String, Integer> registrationAttempts;
private final Set<String> verifiedUsers;
/**
* .
@ -26,6 +28,7 @@ public final class RegistrationService {
this.accountRepository = accountRepository;
this.pendingRegistrations = new ConcurrentHashMap<>();
this.registrationAttempts = new ConcurrentHashMap<>();
this.verifiedUsers = ConcurrentHashMap.newKeySet();
}
/**
@ -38,19 +41,36 @@ public final class RegistrationService {
*/
public boolean initiateRegistration(String username, String email,
DifficultyLevel difficultyLevel) {
if (!EmailService.isValidEmail(email)) {
if (username == null || email == null || difficultyLevel == null) {
return false;
}
if (!accountRepository.registerUser(username, email, difficultyLevel)) {
String normalizedUsername = username.trim();
String normalizedEmail = email.trim();
if (normalizedUsername.isEmpty() || normalizedEmail.isEmpty()) {
return false;
}
if (!EmailService.isValidEmail(normalizedEmail)) {
return false;
}
if (!accountRepository.registerUser(normalizedUsername, normalizedEmail, difficultyLevel)) {
return false; // 用户名已存在或邮箱已注册
}
String registrationCode = EmailService.generateRegistrationCode();
pendingRegistrations.put(username, registrationCode);
registrationAttempts.put(username, 0);
return EmailService.sendRegistrationCode(email, registrationCode);
pendingRegistrations.put(normalizedUsername, registrationCode);
registrationAttempts.put(normalizedUsername, 0);
verifiedUsers.remove(normalizedUsername);
boolean sent = EmailService.sendRegistrationCode(normalizedEmail, registrationCode);
if (!sent) {
pendingRegistrations.remove(normalizedUsername);
registrationAttempts.remove(normalizedUsername);
accountRepository.removeUnverifiedUser(normalizedUsername);
}
return sent;
}
/**
@ -61,25 +81,34 @@ public final class RegistrationService {
* @return truefalse
*/
public boolean verifyRegistrationCode(String username, String registrationCode) {
String storedCode = pendingRegistrations.get(username);
if (storedCode == null || !storedCode.equals(registrationCode)) {
if (username == null || registrationCode == null) {
return false;
}
String normalizedUsername = username.trim();
String trimmedCode = registrationCode.trim();
String storedCode = pendingRegistrations.get(normalizedUsername);
if (storedCode == null || !storedCode.equals(trimmedCode)) {
// 跟踪失败尝试
int attempts = registrationAttempts.getOrDefault(username, 0);
int attempts = registrationAttempts.getOrDefault(normalizedUsername, 0);
attempts++;
registrationAttempts.put(username, attempts);
registrationAttempts.put(normalizedUsername, attempts);
if (attempts >= 3) {
// 如果失败次数过多,则删除用户
pendingRegistrations.remove(username);
registrationAttempts.remove(username);
pendingRegistrations.remove(normalizedUsername);
registrationAttempts.remove(normalizedUsername);
verifiedUsers.remove(normalizedUsername);
accountRepository.removeUnverifiedUser(normalizedUsername);
return false;
}
return false;
}
// 有效码,从待处理列表中移除
pendingRegistrations.remove(username);
registrationAttempts.remove(username);
pendingRegistrations.remove(normalizedUsername);
registrationAttempts.remove(normalizedUsername);
verifiedUsers.add(normalizedUsername);
return true;
}
@ -91,11 +120,23 @@ public final class RegistrationService {
* @return truefalse
*/
public boolean setPassword(String username, String password) {
if (username == null || password == null) {
return false;
}
String normalizedUsername = username.trim();
if (!PasswordValidator.isValidPassword(password)) {
return false;
}
return accountRepository.setPassword(username, password);
if (!verifiedUsers.contains(normalizedUsername)) {
return false;
}
boolean updated = accountRepository.setPassword(normalizedUsername, password);
if (updated) {
verifiedUsers.remove(normalizedUsername);
}
return updated;
}
/**
@ -107,11 +148,14 @@ public final class RegistrationService {
* @return truefalse
*/
public boolean changePassword(String username, String oldPassword, String newPassword) {
if (username == null || oldPassword == null || newPassword == null) {
return false;
}
if (!PasswordValidator.isValidPassword(newPassword)) {
return false;
}
return accountRepository.changePassword(username, oldPassword, newPassword);
return accountRepository.changePassword(username.trim(), oldPassword, newPassword);
}
/**
@ -123,7 +167,10 @@ public final class RegistrationService {
*/
public Optional<com.personalproject.auth.UserAccount> authenticate(String username,
String password) {
return accountRepository.authenticate(username, password);
if (username == null || password == null) {
return Optional.empty();
}
return accountRepository.authenticate(username.trim(), password);
}
/**
@ -133,16 +180,22 @@ public final class RegistrationService {
* @return truefalse
*/
public boolean userExists(String username) {
return accountRepository.userExists(username);
if (username == null) {
return false;
}
return accountRepository.userExists(username.trim());
}
/**
* Gets a user account by username.
*
*
* @param username The username
* @return Optional containing the user account if found
* @param username
* @return Optional
*/
public Optional<com.personalproject.auth.UserAccount> getUser(String username) {
return accountRepository.getUser(username);
if (username == null) {
return Optional.empty();
}
return accountRepository.getUser(username.trim());
}
}
}

@ -87,32 +87,20 @@ public final class QuestionStorageService {
Files.createDirectories(resultsDirectory);
StringBuilder builder = new StringBuilder();
builder.append("考试结果报告").append(System.lineSeparator());
builder.append("考试试卷").append(System.lineSeparator());
builder.append("用户名: ").append(examSession.getUsername()).append(System.lineSeparator());
builder.append("难度: ").append(examSession.getDifficultyLevel().getDisplayName())
.append(System.lineSeparator());
builder.append("开始时间: ").append(examSession.getStartTime()).append(System.lineSeparator());
builder.append("题目数量: ").append(examSession.getQuestions().size())
.append(System.lineSeparator());
builder.append("得分: ").append(String.format("%.2f", examSession.calculateScore())).append("%")
.append(System.lineSeparator());
builder.append(System.lineSeparator());
// 添加逐题结果
// 只保存题目内容
for (int i = 0; i < examSession.getQuestions().size(); i++) {
var question = examSession.getQuestions().get(i);
int userAnswer = examSession.getUserAnswer(i);
boolean isCorrect = question.isAnswerCorrect(userAnswer);
builder.append("题目 ").append(i + 1).append(": ").append(question.getQuestionText())
.append(System.lineSeparator());
builder.append("您的答案: ").append(userAnswer == -1 ? "未回答" :
(userAnswer < question.getOptions().size() ? question.getOptions().get(userAnswer)
: "无效")).append(System.lineSeparator());
builder.append("正确答案: ").append(
question.getOptions().get(question.getCorrectAnswerIndex()))
.append(System.lineSeparator());
builder.append("结果: ").append(isCorrect ? "正确" : "错误").append(System.lineSeparator());
builder.append(System.lineSeparator());
}
@ -159,4 +147,4 @@ public final class QuestionStorageService {
"读取题目文件失败:" + path + ",原因:" + exception.getMessage() + ",将跳过该文件.");
}
}
}
}

@ -16,8 +16,8 @@ import java.util.EnumMap;
import java.util.Map;
/**
* JavaFX GUI Application for the Math Learning Software.
* This is the main entry point for the GUI application.
* JavaFX
*
*/
public final class MathExamGUI extends Application {
@ -25,7 +25,7 @@ public final class MathExamGUI extends Application {
@Override
public void start(Stage primaryStage) {
// Initialize the controller with generators
// 使用题目生成器初始化控制器
Map<DifficultyLevel, QuestionGenerator> generatorMap = new EnumMap<>(DifficultyLevel.class);
generatorMap.put(DifficultyLevel.PRIMARY, new PrimaryQuestionGenerator());
generatorMap.put(DifficultyLevel.MIDDLE, new MiddleSchoolQuestionGenerator());
@ -33,10 +33,10 @@ public final class MathExamGUI extends Application {
QuestionGenerationService questionGenerationService = new QuestionGenerationService(generatorMap);
this.controller = new MathLearningController(generatorMap, questionGenerationService);
// Set up the primary stage
// 配置主舞台
primaryStage.setTitle("数学学习软件");
// Start with login scene
// 从登录界面开始
LoginScene loginScene = new LoginScene(primaryStage, controller);
Scene scene = new Scene(loginScene, 600, 400);
@ -45,11 +45,11 @@ public final class MathExamGUI extends Application {
}
/**
* Launches the JavaFX application.
* JavaFX
*
* @param args Command-line arguments
* @param args
*/
public static void main(String[] args) {
launch(args);
}
}
}

@ -12,7 +12,7 @@ import com.personalproject.ui.views.MainMenuView;
import com.personalproject.ui.scenes.RegistrationScene;
/**
* Scene for handling user login and registration.
*
*/
public class LoginScene extends BorderPane {
@ -24,10 +24,10 @@ public class LoginScene extends BorderPane {
private Button registerButton;
/**
* Constructor for LoginScene.
* LoginScene
*
* @param primaryStage The main stage of the application
* @param controller The math learning controller
* @param primaryStage
* @param controller
*/
public LoginScene(Stage primaryStage, MathLearningController controller) {
this.primaryStage = primaryStage;
@ -36,19 +36,19 @@ public class LoginScene extends BorderPane {
}
/**
* Initializes the UI components.
*
*/
private void initializeUI() {
// Create the main layout
// 创建主布局
VBox mainLayout = new VBox(15);
mainLayout.setAlignment(Pos.CENTER);
mainLayout.setPadding(new Insets(20));
// Title
// 标题
Label titleLabel = new Label("数学学习软件");
titleLabel.setFont(Font.font("System", FontWeight.BOLD, 24));
// Login Form
// 登录表单
GridPane loginForm = new GridPane();
loginForm.setHgap(10);
loginForm.setVgap(10);
@ -67,37 +67,37 @@ public class LoginScene extends BorderPane {
loginForm.add(passwordLabel, 0, 1);
loginForm.add(passwordField, 1, 1);
// Buttons
// 按钮
HBox buttonBox = new HBox(10);
buttonBox.setAlignment(Pos.CENTER);
loginButton = new Button("登录");
registerButton = new Button("注册");
// Set button styles
// 设置按钮样式
loginButton.setPrefWidth(100);
registerButton.setPrefWidth(100);
buttonBox.getChildren().addAll(loginButton, registerButton);
// Add components to main layout
// 将组件添加到主布局
mainLayout.getChildren().addAll(titleLabel, loginForm, buttonBox);
// Set the center of the border pane
// 将主布局放到边界面板中央
setCenter(mainLayout);
// Add event handlers
// 添加事件处理器
addEventHandlers();
}
/**
* Adds event handlers to UI components.
*
*/
private void addEventHandlers() {
loginButton.setOnAction(e -> handleLogin());
registerButton.setOnAction(e -> handleRegistration());
// Allow login with Enter key
// 允许使用回车键登录
setOnKeyPressed(event -> {
if (event.getCode().toString().equals("ENTER")) {
handleLogin();
@ -106,7 +106,7 @@ public class LoginScene extends BorderPane {
}
/**
* Handles the login process.
*
*/
private void handleLogin() {
String username = usernameField.getText().trim();
@ -117,34 +117,34 @@ public class LoginScene extends BorderPane {
return;
}
// Authenticate user
// 验证用户
var userAccount = controller.authenticate(username, password);
if (userAccount.isPresent()) {
// Login successful - navigate to main menu
// 登录成功,跳转到主菜单
MainMenuView mainMenuView = new MainMenuView(primaryStage, controller, userAccount.get());
primaryStage.getScene().setRoot(mainMenuView);
} else {
// Login failed
// 登录失败
showAlert(Alert.AlertType.ERROR, "登录失败", "用户名或密码错误");
}
}
/**
* Handles the registration process.
*
*/
private void handleRegistration() {
// Switch to registration scene
// 切换到注册界面
RegistrationScene registrationScene = new RegistrationScene(primaryStage, controller);
primaryStage.getScene().setRoot(registrationScene);
}
/**
* Shows an alert dialog.
*
*
* @param alertType Type of alert
* @param title Title of the alert
* @param message Message to display
* @param alertType
* @param title
* @param message
*/
private void showAlert(Alert.AlertType alertType, String title, String message) {
Alert alert = new Alert(alertType);
@ -153,4 +153,4 @@ public class LoginScene extends BorderPane {
alert.setContentText(message);
alert.showAndWait();
}
}
}

@ -12,7 +12,7 @@ import com.personalproject.model.DifficultyLevel;
import com.personalproject.ui.scenes.LoginScene;
/**
* Scene for handling user registration.
*
*/
public class RegistrationScene extends BorderPane {
@ -31,10 +31,10 @@ public class RegistrationScene extends BorderPane {
private VBox registrationForm;
/**
* Constructor for RegistrationScene.
* RegistrationScene
*
* @param primaryStage The main stage of the application
* @param controller The math learning controller
* @param primaryStage
* @param controller
*/
public RegistrationScene(Stage primaryStage, MathLearningController controller) {
this.primaryStage = primaryStage;
@ -43,23 +43,23 @@ public class RegistrationScene extends BorderPane {
}
/**
* Initializes the UI components.
*
*/
private void initializeUI() {
// Create the main layout
// 创建主布局
VBox mainLayout = new VBox(15);
mainLayout.setAlignment(Pos.CENTER);
mainLayout.setPadding(new Insets(20));
// Title
// 标题
Label titleLabel = new Label("用户注册");
titleLabel.setFont(Font.font("System", FontWeight.BOLD, 24));
// Registration Form
// 注册表单
registrationForm = new VBox(15);
registrationForm.setAlignment(Pos.CENTER);
// Step 1: Basic Info
// 步骤1填写基础信息
GridPane basicInfoForm = new GridPane();
basicInfoForm.setHgap(10);
basicInfoForm.setVgap(10);
@ -91,7 +91,7 @@ public class RegistrationScene extends BorderPane {
registrationForm.getChildren().addAll(basicInfoForm, sendCodeButton);
// Step 2: Verification (hidden initially)
// 步骤2验证码验证初始隐藏
VBox verificationSection = new VBox(10);
verificationSection.setAlignment(Pos.CENTER);
verificationSection.setVisible(false);
@ -107,7 +107,7 @@ public class RegistrationScene extends BorderPane {
verificationSection.getChildren().addAll(codeLabel, registrationCodeField, verifyCodeButton);
registrationForm.getChildren().add(verificationSection);
// Step 3: Password Setting (hidden initially)
// 步骤3设置密码初始隐藏
VBox passwordSection = new VBox(10);
passwordSection.setAlignment(Pos.CENTER);
passwordSection.setVisible(false);
@ -128,21 +128,21 @@ public class RegistrationScene extends BorderPane {
confirmPasswordField, setPasswordButton);
registrationForm.getChildren().add(passwordSection);
// Back button
// 返回按钮
backButton = new Button("返回");
backButton.setPrefWidth(100);
// Add components to main layout
// 将组件添加到主布局
mainLayout.getChildren().addAll(titleLabel, registrationForm, backButton);
setCenter(mainLayout);
// Add event handlers
// 添加事件处理器
addEventHandlers(sendCodeButton, verificationSection, verifyCodeButton, passwordSection);
}
/**
* Adds event handlers to UI components.
*
*/
private void addEventHandlers(Button sendCodeButton, VBox verificationSection,
Button verifyCodeButton, VBox passwordSection) {
@ -153,7 +153,7 @@ public class RegistrationScene extends BorderPane {
}
/**
* Handles sending registration code.
*
*/
private void handleSendCode(VBox verificationSection) {
String username = usernameField.getText().trim();
@ -170,7 +170,7 @@ public class RegistrationScene extends BorderPane {
return;
}
// Initiate registration
// 发起注册
boolean success = controller.initiateRegistration(username, email, difficultyLevel);
if (success) {
@ -183,7 +183,7 @@ public class RegistrationScene extends BorderPane {
}
/**
* Handles verification of registration code.
*
*/
private void handleVerifyCode(VBox passwordSection) {
String username = usernameField.getText().trim();
@ -206,7 +206,7 @@ public class RegistrationScene extends BorderPane {
}
/**
* Handles setting the user password.
*
*/
private void handleSetPassword() {
String username = usernameField.getText().trim();
@ -233,14 +233,14 @@ public class RegistrationScene extends BorderPane {
if (success) {
showAlert(Alert.AlertType.INFORMATION, "注册成功", "注册成功!请登录。");
handleBack(); // Go back to login screen
handleBack(); // 返回登录界面
} else {
showAlert(Alert.AlertType.ERROR, "设置密码失败", "设置密码失败,请重试。");
}
}
/**
* Handles the back button action.
*
*/
private void handleBack() {
LoginScene loginScene = new LoginScene(primaryStage, controller);
@ -248,11 +248,11 @@ public class RegistrationScene extends BorderPane {
}
/**
* Shows an alert dialog.
*
*
* @param alertType Type of alert
* @param title Title of the alert
* @param message Message to display
* @param alertType
* @param title
* @param message
*/
private void showAlert(Alert.AlertType alertType, String title, String message) {
Alert alert = new Alert(alertType);
@ -261,4 +261,4 @@ public class RegistrationScene extends BorderPane {
alert.setContentText(message);
alert.showAndWait();
}
}
}

@ -13,7 +13,7 @@ import com.personalproject.auth.UserAccount;
import com.personalproject.ui.views.MainMenuView;
/**
* View for displaying exam results.
*
*/
public class ExamResultsView extends BorderPane {
@ -24,11 +24,11 @@ public class ExamResultsView extends BorderPane {
private Button exitButton;
/**
* Constructor for ExamResultsView.
* ExamResultsView
*
* @param primaryStage The main stage of the application
* @param controller The math learning controller
* @param examSession The completed exam session
* @param primaryStage
* @param controller
* @param examSession
*/
public ExamResultsView(Stage primaryStage, MathLearningController controller, ExamSession examSession) {
this.primaryStage = primaryStage;
@ -38,24 +38,24 @@ public class ExamResultsView extends BorderPane {
}
/**
* Initializes the UI components.
*
*/
private void initializeUI() {
// Create the main layout
// 创建主布局
VBox mainLayout = new VBox(20);
mainLayout.setAlignment(Pos.CENTER);
mainLayout.setPadding(new Insets(20));
// Results title
// 结果标题
Label titleLabel = new Label("考试结果");
titleLabel.setFont(Font.font("System", FontWeight.BOLD, 24));
// Score display
// 分数展示
double score = examSession.calculateScore();
Label scoreLabel = new Label(String.format("您的得分: %.2f%%", score));
scoreLabel.setFont(Font.font("System", FontWeight.BOLD, 18));
// Performance breakdown
// 成绩明细
VBox breakdownBox = new VBox(10);
breakdownBox.setAlignment(Pos.CENTER);
@ -65,31 +65,31 @@ public class ExamResultsView extends BorderPane {
breakdownBox.getChildren().addAll(totalQuestionsLabel, correctAnswersLabel, incorrectAnswersLabel);
// Buttons
// 按钮区域
HBox buttonBox = new HBox(15);
buttonBox.setAlignment(Pos.CENTER);
continueButton = new Button("继续考试");
exitButton = new Button("退出");
// Set button sizes
// 设置按钮尺寸
continueButton.setPrefSize(120, 40);
exitButton.setPrefSize(120, 40);
buttonBox.getChildren().addAll(continueButton, exitButton);
// Add components to main layout
// 将组件添加到主布局
mainLayout.getChildren().addAll(titleLabel, scoreLabel, breakdownBox, buttonBox);
// Set the center of the border pane
// 将主布局置于边界面板中央
setCenter(mainLayout);
// Add event handlers
// 添加事件处理器
addEventHandlers();
}
/**
* Adds event handlers to UI components.
*
*/
private void addEventHandlers() {
continueButton.setOnAction(e -> handleContinue());
@ -97,10 +97,10 @@ public class ExamResultsView extends BorderPane {
}
/**
* Handles the continue button action.
*
*/
private void handleContinue() {
// Go back to main menu to start a new exam
// 返回主菜单以开始新考试
controller.getUserAccount(examSession.getUsername())
.ifPresentOrElse(
userAccount -> {
@ -108,9 +108,9 @@ public class ExamResultsView extends BorderPane {
primaryStage.getScene().setRoot(mainMenuView);
},
() -> {
// If user account can't be found, show an error and go back to login
// 如果找不到用户信息,则提示错误并返回登录界面
showAlert(Alert.AlertType.ERROR, "错误", "用户信息无法找到,请重新登录");
// Go back to login scene
// 返回登录场景
com.personalproject.ui.scenes.LoginScene loginScene =
new com.personalproject.ui.scenes.LoginScene(primaryStage, controller);
primaryStage.getScene().setRoot(loginScene);
@ -119,10 +119,10 @@ public class ExamResultsView extends BorderPane {
}
/**
* Handles the exit button action.
* 退
*/
private void handleExit() {
// Go back to main menu
// 返回主菜单
controller.getUserAccount(examSession.getUsername())
.ifPresentOrElse(
userAccount -> {
@ -130,9 +130,9 @@ public class ExamResultsView extends BorderPane {
primaryStage.getScene().setRoot(mainMenuView);
},
() -> {
// If user account can't be found, show an error and go back to login
// 如果找不到用户信息,则提示错误并返回登录界面
showAlert(Alert.AlertType.ERROR, "错误", "用户信息无法找到,请重新登录");
// Go back to login scene
// 返回登录场景
com.personalproject.ui.scenes.LoginScene loginScene =
new com.personalproject.ui.scenes.LoginScene(primaryStage, controller);
primaryStage.getScene().setRoot(loginScene);
@ -141,11 +141,11 @@ public class ExamResultsView extends BorderPane {
}
/**
* Shows an alert dialog.
*
*
* @param alertType Type of alert
* @param title Title of the alert
* @param message Message to display
* @param alertType
* @param title
* @param message
*/
private void showAlert(Alert.AlertType alertType, String title, String message) {
Alert alert = new Alert(alertType);
@ -154,4 +154,4 @@ public class ExamResultsView extends BorderPane {
alert.setContentText(message);
alert.showAndWait();
}
}
}

@ -12,7 +12,7 @@ import com.personalproject.model.DifficultyLevel;
import com.personalproject.auth.UserAccount;
/**
* View for selecting exam difficulty and number of questions.
*
*/
public class ExamSelectionView extends BorderPane {
@ -25,11 +25,11 @@ public class ExamSelectionView extends BorderPane {
private Button backButton;
/**
* Constructor for ExamSelectionView.
* ExamSelectionView
*
* @param primaryStage The main stage of the application
* @param controller The math learning controller
* @param userAccount The current user account
* @param primaryStage
* @param controller
* @param userAccount
*/
public ExamSelectionView(Stage primaryStage, MathLearningController controller, UserAccount userAccount) {
this.primaryStage = primaryStage;
@ -39,19 +39,19 @@ public class ExamSelectionView extends BorderPane {
}
/**
* Initializes the UI components.
*
*/
private void initializeUI() {
// Create the main layout
// 创建主布局
VBox mainLayout = new VBox(20);
mainLayout.setAlignment(Pos.CENTER);
mainLayout.setPadding(new Insets(20));
// Title
// 标题
Label titleLabel = new Label("考试设置");
titleLabel.setFont(Font.font("System", FontWeight.BOLD, 24));
// Form for exam settings
// 考试设置表单
GridPane examSettingsForm = new GridPane();
examSettingsForm.setHgap(15);
examSettingsForm.setVgap(15);
@ -60,11 +60,11 @@ public class ExamSelectionView extends BorderPane {
Label difficultyLabel = new Label("选择难度:");
difficultyComboBox = new ComboBox<>();
difficultyComboBox.getItems().addAll(DifficultyLevel.PRIMARY, DifficultyLevel.MIDDLE, DifficultyLevel.HIGH);
difficultyComboBox.setValue(userAccount.difficultyLevel()); // Default to user's difficulty
difficultyComboBox.setValue(userAccount.difficultyLevel()); // 默认选中用户的难度
difficultyComboBox.setPrefWidth(200);
Label questionCountLabel = new Label("题目数量 (10-30):");
questionCountSpinner = new Spinner<>(10, 30, 10); // min, max, initial value
questionCountSpinner = new Spinner<>(10, 30, 10); // 最小值、最大值、初始值
questionCountSpinner.setPrefWidth(200);
examSettingsForm.add(difficultyLabel, 0, 0);
@ -72,31 +72,31 @@ public class ExamSelectionView extends BorderPane {
examSettingsForm.add(questionCountLabel, 0, 1);
examSettingsForm.add(questionCountSpinner, 1, 1);
// Buttons
// 按钮区域
HBox buttonBox = new HBox(15);
buttonBox.setAlignment(Pos.CENTER);
startExamButton = new Button("开始考试");
backButton = new Button("返回");
// Set button sizes
// 设置按钮尺寸
startExamButton.setPrefSize(120, 40);
backButton.setPrefSize(120, 40);
buttonBox.getChildren().addAll(startExamButton, backButton);
// Add components to main layout
// 将组件添加到主布局
mainLayout.getChildren().addAll(titleLabel, examSettingsForm, buttonBox);
// Set the center of the border pane
// 将主布局置于边界面板中央
setCenter(mainLayout);
// Add event handlers
// 添加事件处理器
addEventHandlers();
}
/**
* Adds event handlers to UI components.
*
*/
private void addEventHandlers() {
startExamButton.setOnAction(e -> handleStartExam());
@ -104,7 +104,7 @@ public class ExamSelectionView extends BorderPane {
}
/**
* Handles the start exam button action.
*
*/
private void handleStartExam() {
DifficultyLevel selectedDifficulty = difficultyComboBox.getValue();
@ -115,7 +115,7 @@ public class ExamSelectionView extends BorderPane {
return;
}
// Create and start exam session
// 创建并启动考试会话
com.personalproject.model.ExamSession examSession = controller.createExamSession(
userAccount.username(), selectedDifficulty, questionCount);
@ -124,7 +124,7 @@ public class ExamSelectionView extends BorderPane {
}
/**
* Handles the back button action.
*
*/
private void handleBack() {
MainMenuView mainMenuView = new MainMenuView(primaryStage, controller, userAccount);
@ -132,11 +132,11 @@ public class ExamSelectionView extends BorderPane {
}
/**
* Shows an alert dialog.
*
*
* @param alertType Type of alert
* @param title Title of the alert
* @param message Message to display
* @param alertType
* @param title
* @param message
*/
private void showAlert(Alert.AlertType alertType, String title, String message) {
Alert alert = new Alert(alertType);
@ -145,4 +145,4 @@ public class ExamSelectionView extends BorderPane {
alert.setContentText(message);
alert.showAndWait();
}
}
}

@ -13,7 +13,7 @@ import com.personalproject.model.QuizQuestion;
import com.personalproject.ui.views.ExamResultsView;
/**
* View for taking the exam with questions and answer options.
*
*/
public class ExamView extends BorderPane {
@ -30,11 +30,11 @@ public class ExamView extends BorderPane {
private HBox buttonBox;
/**
* Constructor for ExamView.
* ExamView
*
* @param primaryStage The main stage of the application
* @param controller The math learning controller
* @param examSession The current exam session
* @param primaryStage
* @param controller
* @param examSession
*/
public ExamView(Stage primaryStage, MathLearningController controller, ExamSession examSession) {
this.primaryStage = primaryStage;
@ -44,29 +44,30 @@ public class ExamView extends BorderPane {
}
/**
* Initializes the UI components.
*
*/
private void initializeUI() {
// Create the main layout
// 创建主布局
VBox mainLayout = new VBox(20);
mainLayout.setAlignment(Pos.CENTER);
mainLayout.setPadding(new Insets(20));
// Question number
// 题号
questionNumberLabel = new Label();
questionNumberLabel.setFont(Font.font("System", FontWeight.BOLD, 16));
// Question text
// 题目文本
questionTextLabel = new Label();
questionTextLabel.setWrapText(true);
questionTextLabel.setFont(Font.font("System", FontWeight.NORMAL, 14));
questionTextLabel.setMaxWidth(500);
// Options
// 选项容器
optionsBox = new VBox(10);
optionsBox.setPadding(new Insets(10));
answerToggleGroup = new ToggleGroup();
// Buttons
// 按钮区域
buttonBox = new HBox(15);
buttonBox.setAlignment(Pos.CENTER);
@ -74,34 +75,34 @@ public class ExamView extends BorderPane {
nextButton = new Button("下一题");
finishButton = new Button("完成考试");
// Set button sizes
// 设置按钮尺寸
previousButton.setPrefSize(100, 35);
nextButton.setPrefSize(100, 35);
finishButton.setPrefSize(120, 35);
buttonBox.getChildren().addAll(previousButton, nextButton, finishButton);
// Add components to main layout
// 将组件添加到主布局
mainLayout.getChildren().addAll(questionNumberLabel, questionTextLabel, optionsBox, buttonBox);
// Set the center of the border pane
// 将主布局置于边界面板中央
setCenter(mainLayout);
// Load the first question
// 加载第一题
loadCurrentQuestion();
// Add event handlers
// 添加事件处理器
addEventHandlers();
}
/**
* Loads the current question into the UI.
*
*/
private void loadCurrentQuestion() {
try {
// Check if exam is complete before loading next question
// 在加载下一题之前检查考试是否已完成
if (examSession.isComplete()) {
// If exam is complete, the finish button should be enabled
// 如果考试已完成,则启用“完成考试”按钮
updateButtonStates();
return;
}
@ -114,23 +115,23 @@ public class ExamView extends BorderPane {
return;
}
// Update question number and text
// 更新题号与题目文本
questionNumberLabel.setText("第 " + (currentIndex + 1) + " 题");
questionTextLabel.setText(currentQuestion.getQuestionText());
// Clear previous options
// 清空上一题的选项
answerToggleGroup.selectToggle(null);
answerToggleGroup.getToggles().clear();
optionsBox.getChildren().clear();
// Create new options
answerToggleGroup = new ToggleGroup();
// 创建新的选项组件
for (int i = 0; i < currentQuestion.getOptions().size(); i++) {
String option = currentQuestion.getOptions().get(i);
RadioButton optionButton = new RadioButton((i + 1) + ". " + option);
optionButton.setToggleGroup(answerToggleGroup);
optionButton.setUserData(i); // Store option index
// If this question already has an answer, select it
optionButton.setUserData(i); // 存储选项索引
// 如果该题已有答案则自动选中
if (examSession.hasAnswered(currentIndex) &&
examSession.getUserAnswer(currentIndex) == i) {
optionButton.setSelected(true);
@ -139,7 +140,7 @@ public class ExamView extends BorderPane {
optionsBox.getChildren().add(optionButton);
}
// Update button states
// 更新按钮状态
updateButtonStates();
} catch (Exception e) {
showAlert(Alert.AlertType.ERROR, "错误", "加载题目时发生错误: " + e.getMessage());
@ -147,50 +148,50 @@ public class ExamView extends BorderPane {
}
/**
* Updates the state of navigation buttons based on current position.
*
*/
private void updateButtonStates() {
try {
int currentIndex = examSession.getCurrentQuestionIndex();
int totalQuestions = examSession.getTotalQuestions();
// Handle potential edge cases
// 处理潜在极端情况
if (totalQuestions <= 0) {
// If there are no questions, disable all navigation
// 如果没有题目,则禁用所有导航按钮
previousButton.setDisable(true);
nextButton.setDisable(true);
finishButton.setDisable(false); // Allow finishing exam
finishButton.setDisable(false); // 仍允许完成考试
return;
}
// Previous button state
// “上一题”按钮状态
previousButton.setDisable(currentIndex < 0 || currentIndex == 0);
// Next button state
// “下一题”按钮状态
nextButton.setDisable(currentIndex < 0 || currentIndex >= totalQuestions - 1);
// Finish button state - enabled when exam is complete or at the last question
// “完成考试”按钮状态——在考试完成或到达最后一题时启用
boolean isExamComplete = examSession.isComplete();
boolean isAtLastQuestion = (currentIndex >= totalQuestions - 1);
finishButton.setDisable(!(isExamComplete || isAtLastQuestion));
} catch (Exception e) {
// In case of any error, disable navigation buttons to prevent further issues
// 若出现异常,禁用导航按钮以避免进一步问题
previousButton.setDisable(true);
nextButton.setDisable(true);
finishButton.setDisable(false); // Still allow finishing
finishButton.setDisable(false); // 仍允许完成考试
showAlert(Alert.AlertType.ERROR, "错误", "更新按钮状态时发生错误: " + e.getMessage());
}
}
/**
* Adds event handlers to UI components.
*
*/
private void addEventHandlers() {
nextButton.setOnAction(e -> handleNextQuestion());
previousButton.setOnAction(e -> handlePreviousQuestion());
finishButton.setOnAction(e -> handleFinishExam());
// Add change listener to save answer when an option is selected
// 添加变更监听器,在选项被选择时保存答案
answerToggleGroup.selectedToggleProperty().addListener((obs, oldSelection, newSelection) -> {
if (newSelection != null) {
int selectedIndex = (Integer) newSelection.getUserData();
@ -200,15 +201,15 @@ public class ExamView extends BorderPane {
}
/**
* Handles the next question button action.
*
*/
private void handleNextQuestion() {
try {
if (examSession.goToNextQuestion()) {
loadCurrentQuestion();
} else {
// If we can't go to next question, we might be at the end
// Check if exam is complete and update button states accordingly
// 若无法跳转到下一题,可能已经到达末尾
// 检查考试是否完成并据此更新按钮状态
updateButtonStates();
}
} catch (Exception e) {
@ -217,14 +218,14 @@ public class ExamView extends BorderPane {
}
/**
* Handles the previous question button action.
*
*/
private void handlePreviousQuestion() {
try {
if (examSession.goToPreviousQuestion()) {
loadCurrentQuestion();
} else {
// If we can't go to previous question, we might be at the beginning
// 若无法返回上一题,可能已经位于开头
updateButtonStates();
}
} catch (Exception e) {
@ -233,11 +234,11 @@ public class ExamView extends BorderPane {
}
/**
* Shows an alert dialog.
*
*
* @param alertType Type of alert
* @param title Title of the alert
* @param message Message to display
* @param alertType
* @param title
* @param message
*/
private void showAlert(Alert.AlertType alertType, String title, String message) {
Alert alert = new Alert(alertType);
@ -248,14 +249,14 @@ public class ExamView extends BorderPane {
}
/**
* Handles the finish exam button action.
*
*/
private void handleFinishExam() {
// Save exam results
// 保存考试结果
controller.saveExamResults(examSession);
// Show results
// 展示考试结果
ExamResultsView resultsView = new ExamResultsView(primaryStage, controller, examSession);
primaryStage.getScene().setRoot(resultsView);
}
}
}

@ -14,7 +14,7 @@ import com.personalproject.auth.UserAccount;
import com.personalproject.ui.scenes.LoginScene;
/**
* View for the main menu where users can start exams or change settings.
*
*/
public class MainMenuView extends BorderPane {
@ -26,11 +26,11 @@ public class MainMenuView extends BorderPane {
private Button logoutButton;
/**
* Constructor for MainMenuView.
* MainMenuView
*
* @param primaryStage The main stage of the application
* @param controller The math learning controller
* @param userAccount The current user account
* @param primaryStage
* @param controller
* @param userAccount
*/
public MainMenuView(Stage primaryStage, MathLearningController controller, UserAccount userAccount) {
this.primaryStage = primaryStage;
@ -40,23 +40,23 @@ public class MainMenuView extends BorderPane {
}
/**
* Initializes the UI components.
*
*/
private void initializeUI() {
// Create the main layout
// 创建主布局
VBox mainLayout = new VBox(20);
mainLayout.setAlignment(Pos.CENTER);
mainLayout.setPadding(new Insets(20));
// Welcome message
// 欢迎信息
Label welcomeLabel = new Label("欢迎, " + userAccount.username());
welcomeLabel.setFont(Font.font("System", FontWeight.BOLD, 18));
// Difficulty info
// 难度信息
Label difficultyLabel = new Label("当前难度: " + userAccount.difficultyLevel().getDisplayName());
difficultyLabel.setFont(Font.font("System", FontWeight.NORMAL, 14));
// Buttons
// 按钮区域
VBox buttonBox = new VBox(15);
buttonBox.setAlignment(Pos.CENTER);
@ -64,25 +64,25 @@ public class MainMenuView extends BorderPane {
changePasswordButton = new Button("修改密码");
logoutButton = new Button("退出登录");
// Set button sizes
// 设置按钮尺寸
startExamButton.setPrefSize(150, 40);
changePasswordButton.setPrefSize(150, 40);
logoutButton.setPrefSize(150, 40);
buttonBox.getChildren().addAll(startExamButton, changePasswordButton, logoutButton);
// Add components to main layout
// 将组件添加到主布局
mainLayout.getChildren().addAll(welcomeLabel, difficultyLabel, buttonBox);
// Set the center of the border pane
// 将主布局置于边界面板中央
setCenter(mainLayout);
// Add event handlers
// 添加事件处理器
addEventHandlers();
}
/**
* Adds event handlers to UI components.
*
*/
private void addEventHandlers() {
startExamButton.setOnAction(e -> handleStartExam());
@ -91,7 +91,7 @@ public class MainMenuView extends BorderPane {
}
/**
* Handles the start exam button action.
*
*/
private void handleStartExam() {
ExamSelectionView examSelectionView = new ExamSelectionView(primaryStage, controller, userAccount);
@ -99,7 +99,7 @@ public class MainMenuView extends BorderPane {
}
/**
* Handles the change password button action.
*
*/
private void handleChangePassword() {
PasswordChangeView passwordChangeView = new PasswordChangeView(primaryStage, controller, userAccount);
@ -107,11 +107,11 @@ public class MainMenuView extends BorderPane {
}
/**
* Handles the logout button action.
* 退
*/
private void handleLogout() {
// Go back to login screen
// 返回登录界面
LoginScene loginScene = new LoginScene(primaryStage, controller);
primaryStage.getScene().setRoot(loginScene);
}
}
}

@ -12,7 +12,7 @@ import com.personalproject.auth.UserAccount;
import com.personalproject.ui.views.MainMenuView;
/**
* View for changing user password.
*
*/
public class PasswordChangeView extends BorderPane {
@ -26,11 +26,11 @@ public class PasswordChangeView extends BorderPane {
private Button backButton;
/**
* Constructor for PasswordChangeView.
* PasswordChangeView
*
* @param primaryStage The main stage of the application
* @param controller The math learning controller
* @param userAccount The current user account
* @param primaryStage
* @param controller
* @param userAccount
*/
public PasswordChangeView(Stage primaryStage, MathLearningController controller, UserAccount userAccount) {
this.primaryStage = primaryStage;
@ -40,19 +40,19 @@ public class PasswordChangeView extends BorderPane {
}
/**
* Initializes the UI components.
*
*/
private void initializeUI() {
// Create the main layout
// 创建主布局
VBox mainLayout = new VBox(20);
mainLayout.setAlignment(Pos.CENTER);
mainLayout.setPadding(new Insets(20));
// Title
// 标题
Label titleLabel = new Label("修改密码");
titleLabel.setFont(Font.font("System", FontWeight.BOLD, 24));
// Form for password change
// 修改密码表单
GridPane passwordForm = new GridPane();
passwordForm.setHgap(15);
passwordForm.setVgap(15);
@ -77,31 +77,31 @@ public class PasswordChangeView extends BorderPane {
passwordForm.add(confirmNewPasswordLabel, 0, 2);
passwordForm.add(confirmNewPasswordField, 1, 2);
// Buttons
// 按钮区域
HBox buttonBox = new HBox(15);
buttonBox.setAlignment(Pos.CENTER);
changePasswordButton = new Button("修改密码");
backButton = new Button("返回");
// Set button sizes
// 设置按钮尺寸
changePasswordButton.setPrefSize(120, 40);
backButton.setPrefSize(120, 40);
buttonBox.getChildren().addAll(changePasswordButton, backButton);
// Add components to main layout
// 将组件添加到主布局
mainLayout.getChildren().addAll(titleLabel, passwordForm, buttonBox);
// Set the center of the border pane
// 将主布局置于边界面板中央
setCenter(mainLayout);
// Add event handlers
// 添加事件处理器
addEventHandlers();
}
/**
* Adds event handlers to UI components.
*
*/
private void addEventHandlers() {
changePasswordButton.setOnAction(e -> handleChangePassword());
@ -109,7 +109,7 @@ public class PasswordChangeView extends BorderPane {
}
/**
* Handles the change password button action.
*
*/
private void handleChangePassword() {
String oldPassword = oldPasswordField.getText();
@ -136,14 +136,14 @@ public class PasswordChangeView extends BorderPane {
if (success) {
showAlert(Alert.AlertType.INFORMATION, "修改成功", "密码修改成功!");
handleBack(); // Go back to main menu
handleBack(); // 返回主菜单
} else {
showAlert(Alert.AlertType.ERROR, "修改失败", "当前密码错误或修改失败");
}
}
/**
* Handles the back button action.
*
*/
private void handleBack() {
MainMenuView mainMenuView = new MainMenuView(primaryStage, controller, userAccount);
@ -151,11 +151,11 @@ public class PasswordChangeView extends BorderPane {
}
/**
* Shows an alert dialog.
*
*
* @param alertType Type of alert
* @param title Title of the alert
* @param message Message to display
* @param alertType
* @param title
* @param message
*/
private void showAlert(Alert.AlertType alertType, String title, String message) {
Alert alert = new Alert(alertType);
@ -164,4 +164,4 @@ public class PasswordChangeView extends BorderPane {
alert.setContentText(message);
alert.showAndWait();
}
}
}

@ -0,0 +1,20 @@
# 主机不变
mail.smtp.host=smtp.126.com
# 关键修改:端口改为 465
mail.smtp.port=465
# 关键修改:禁用 STARTTLS
mail.smtp.starttls.enable=false
# 关键修改:启用 SSL
mail.smtp.ssl.enable=true
# 以下不变
mail.smtp.auth=true
mail.username=soloyouth@126.com
mail.password=ZYsjxwDXFBsWeQcX
mail.from=soloyouth@126.com
mail.subject=数学学习软件注册验证码
mail.debug=true
Loading…
Cancel
Save