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

这篇博客探讨了如何判断用户输入的逻辑表达式是否结构正确,以确保它们可以得出真或假的结果。作者使用了JavaScript的ScriptEngine来评估表达式,通过eval()方法检查结果是否为布尔类型。有效表达式包括比较和逻辑运算符,如1==1或1<2,而无效表达式则缺少正确的结构,如11+1。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值