当前位置:   article > 正文

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

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

程序结构设计

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");
        }
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97

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);
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

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

3.1 interface

package com.example.demo.expression;

public interface Expression {
    int interpret();
}
  • 1
  • 2
  • 3
  • 4
  • 5
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;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
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();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
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();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
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();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
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");
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/85989
推荐阅读
相关标签
  

闽ICP备14008679号