Java开发四则运算-使用递归和解释器模式

使用递归和解释器模式

  • 程序结构设计
  • 具体实现
    • 1. 先上最重要的实现类:ExpressionParser(最重要)
    • 2. 再上上下文测试代码:Context(程序入口,稍重要)
    • 3. 使用到的接口和数据结构(不太重要的结构封装)
      • 3.1 interface
        • 3.1.1 NumberExpression
        • 3.1.2 四则运算Expression实现类
          • 3.1.2.1 AddExpression
          • 3.1.2.2 SubtractExpression
          • 3.1.2.3 MultiplyExpression
          • 3.1.2.4 DivideExpression

程序结构设计

Context 编写测试代码
expression
Expression interface
四则运算Expression implement
NumberExpression implement
ExpressionParser 核心实现类

具体实现

1. 先上最重要的实现类:ExpressionParser(最重要)

package com.example.demo;

import com.example.demo.expression.*;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ExpressionParser {
    private String input;
    private int index;

    public ExpressionParser(String input) {
        this.input = input.replaceAll("\\s", ""); // 移除空格
        this.index = 0;
    }

    public Expression parse() {
        return parseExpression();
    }

    private Expression parseExpression() {
        Expression left = parseTerm();

        while (index < input.length()) {
            char operator = input.charAt(index);
            if (operator == '+' || operator == '-') {
                index++;
                Expression right = parseTerm();

                if (operator == '+') {
                    left = new AddExpression(left, right);
                } else {
                    left = new SubtractExpression(left, right);
                }
            } else {
                break;
            }
        }

        return left;
    }

    private Expression parseTerm() {
        Expression left = parseFactor();

        while (index < input.length()) {
            char operator = input.charAt(index);
            if (operator == '*' || operator == '/') {
                index++;
                Expression right = parseFactor();

                if (operator == '*') {
                    left = new MultiplyExpression(left, right);
                } else {
                    left = new DivideExpression(left, right);
                }
            } else {
                break;
            }
        }

        return left;
    }

    private Expression parseFactor() {
        if (index < input.length()) {
            char currentChar = input.charAt(index);
            if (Character.isDigit(currentChar)) {
                return parseNumber();
            } else if (currentChar == '(') {
                index++;
                Expression expression = parseExpression();
                if (index < input.length() && input.charAt(index) == ')') {
                    index++;
                    return expression;
                } else {
                    throw new IllegalArgumentException("Mismatched parentheses");
                }
            }
        }

        throw new IllegalArgumentException("Invalid expression");
    }

    private Expression parseNumber() {
        Pattern numberPattern = Pattern.compile("\\d+");
        Matcher matcher = numberPattern.matcher(input.substring(index));
        if (matcher.find()) {
            String numberStr = matcher.group();
            index += numberStr.length();
            return new NumberExpression(Integer.parseInt(numberStr));
        } else {
            throw new IllegalArgumentException("Invalid number");
        }
    }
}

2. 再上上下文测试代码:Context(程序入口,稍重要)

package com.example.demo;

import com.example.demo.expression.Expression;

public class Context {
    public static void main(String[] args) {
        String inputExpression = "(3 + 55) * 2 - 4 / 2";
        ExpressionParser parser = new ExpressionParser(inputExpression);
        Expression expression = parser.parse();

        int result = expression.interpret();
        System.out.println("Result: " + result);
    }
}

3. 使用到的接口和数据结构(不太重要的结构封装)

3.1 interface

package com.example.demo.expression;

public interface Expression {
    int interpret();
}
3.1.1 NumberExpression
package com.example.demo;

import com.example.demo.expression.Expression;

public class NumberExpression implements Expression {
    private int number;

    public NumberExpression(int number) {
        this.number = number;
    }

    @Override
    public int interpret() {
        return number;
    }
}
3.1.2 四则运算Expression实现类
3.1.2.1 AddExpression
package com.example.demo.expression;

public class AddExpression implements Expression {
    private Expression left;
    private Expression right;

    public AddExpression(Expression left, Expression right) {
        this.left = left;
        this.right = right;
    }

    @Override
    public int interpret() {
        return left.interpret() + right.interpret();
    }
}
3.1.2.2 SubtractExpression
package com.example.demo.expression;

// 非终结符表达式:减法表达式
public class SubtractExpression implements Expression {
    private Expression left;
    private Expression right;

    public SubtractExpression(Expression left, Expression right) {
        this.left = left;
        this.right = right;
    }

    @Override
    public int interpret() {
        return left.interpret() - right.interpret();
    }
}
3.1.2.3 MultiplyExpression
package com.example.demo.expression;

// 非终结符表达式:乘法表达式
public class MultiplyExpression implements Expression {
    private Expression left;
    private Expression right;

    public MultiplyExpression(Expression left, Expression right) {
        this.left = left;
        this.right = right;
    }

    @Override
    public int interpret() {
        return left.interpret() * right.interpret();
    }
}
3.1.2.4 DivideExpression
package com.example.demo.expression;

// 非终结符表达式:除法表达式
public class DivideExpression implements Expression {
    private Expression left;
    private Expression right;

    public DivideExpression(Expression left, Expression right) {
        this.left = left;
        this.right = right;
    }

    @Override
    public int interpret() {
        int divisor = right.interpret();
        if (divisor != 0) {
            return left.interpret() / divisor;
        } else {
            throw new ArithmeticException("Division by zero");
        }
    }
}

你可能感兴趣的:(java,解释器模式,设计模式,数据结构)