java 逻辑表达式 判断,Java:构建逻辑表达式,然后验证它们

I have a little functionality where I need to determine whether a rule that a user is creating is syntactically valid.

That being said the structure of what I'm building are like the following:

1 == 1

1 + 1 == 1

1 + 1 == 1 OR 1 == 1

More combinations of the above examples

These expressions are saved in a string variable, e.g:

String expression = "";

while(items.hasNext())

{

String currentItem = items.next();

expression += currentItem.value();

}

//Check if the expression is valid

VALID EXPRESSIONS

Valid expressions are the ones that have a logic operator (, >) and the output would be true or false (doesn't matter which)

1 == 1

1 < 2

1 == 1 OR 1 < 4

4 == 9 OR 9 == 3

INVALID EXPRESSIONS

Invalid expressions are the ones that doesn't have the proper structure in order to determine whether that expression is true or false.

1

1+1

1===

==1

1

11 (that is number then number)

NOTE

I've tried using

Boolean.valueOf(String)

Boolean.parse(String)

Other types of Boolean methods

解决方案

EDIT Will now not allow any expression to be success.

EDIT2 Examples of what evaluates.

import javax.script.ScriptEngineManager;

import javax.script.*;

public class HelloWorld{

public static void main(String[] args)

{

ScriptEngineManager manager = new ScriptEngineManager();

ScriptEngine engine = manager.getEngineByName("JavaScript");

String expression = "1+2"; // evaluates to Failure: 3

String expression = "1+a"; // evaluates to Failure:

String expression = "1==1"; // evaluates to Success: true

String expression = "1==2"; // evaluates to Failure: false

try

{

Object result = engine.eval(expression);

if(result instanceof Boolean)

{

System.out.print("Success: ");

System.out.println(result);

}

else

{

System.out.print("Failure: ");

System.out.println(result);

}

}

catch(ScriptException e)

{

// handle

System.out.println("Failure");

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值