@ -0,0 +1,62 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,30 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,40 @@
|
||||
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");
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,37 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,39 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,31 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,17 @@
|
||||
package com.personalproject.generator;
|
||||
|
||||
import java.util.Random;
|
||||
|
||||
/**
|
||||
* 负责生成单条数学题目的表达式.
|
||||
*/
|
||||
public interface QuestionGenerator {
|
||||
|
||||
/**
|
||||
* 基于提供的随机数生成器构造一道题目的表达式.
|
||||
*
|
||||
* @param random 用于生成随机数的实例.
|
||||
* @return 生成的题目表达式.
|
||||
*/
|
||||
String generateQuestion(Random random);
|
||||
}
|
||||
@ -0,0 +1,195 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,73 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,217 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
Loading…
Reference in new issue