【问题标题】:Evaluate expression for specific requirement in java评估java中特定要求的表达式
【发布时间】:2016-11-14 14:37:31
【问题描述】:

我有 Expression 对象,它具有以下内容:

  1. 操作员
  2. 参数
  3. 价值

提到的每个简单表达式都可以组合成一个复合表达式。

public SimpleExpresssion createcompound(SimpleExpression simple1,SimpleExpression simple2)    
    {
        CompoundExpression ce = new CompoundExpression();
        ce.lhs(simple1);
        ce.rhs(simple2);
        ce.operator(AND);    
    }

一个复杂的例子看起来像 ((1AND2)OR(3OR4)) 其中 1,2,3,4 是 Expression 对象。 我正在寻找一种逻辑来根据表达式中的括号偏好来评估表达式。 笔记: CompoundExpressionExpression 的扩展类,因此最终输出是一个 Expression 对象。 容易解决吗?如果不是我的选择是什么

【问题讨论】:

    标签: java expression expression-evaluation


    【解决方案1】:

    复杂的表达式 ((1AND2)OR(3OR4)) 可以重写为前缀表示法:

    OR(AND(1,2), OR(3,4))
    

    因此,您唯一需要的是具有 3 个参数的 CompoundExpression 的构造函数或工厂方法:运算符、左右抽象表达式:

    CompoundExpression(Operator o, Expression left, Expression right) {
        this.operator = operator;
        this.left = left;
        this.right = right;
    }
    

    然后,假设您有 4 个简单的表达式,构建结果表达式很简单:

    Expression result = new CompoundExpression(OR, 
        new CompoundExpression(AND, simple1, simple2), 
        new CompoundExpression(OR, simple3, simple4)
    );
    

    【讨论】:

    • 提供的解决方案似乎是要走的路。可以概括吗?
    • 我不确定你想要达到什么目的。使用这些类,您可以手动构建任何表达式的抽象语法树 (AST)。
    • 我想评估表达式。我做了首先将其转换为后缀表达式并使用堆栈对其进行评估的解决方案
    【解决方案2】:
    1. 将表达式转换为等效的后缀表达式。
    2. 使用堆栈计算后缀表达式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-26
      • 1970-01-01
      • 2016-08-03
      • 2022-11-07
      • 1970-01-01
      • 2012-12-27
      • 1970-01-01
      相关资源
      最近更新 更多