Java:构建逻辑表达式,然后对其进行验证

编程入门 行业动态 更新时间:2024-10-13 12:16:40
本文介绍了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或1 == 1
  • 以上示例的更多组合

这些表达式保存在字符串变量中,例如:

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

有效表达

有效表达式是具有逻辑运算符(<,< =,==,=>,>)的表达式,并且输出将为true或false(无关紧要)

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或1< 4
  • 4 == 9或9 == 3

无效的表达

无效的表达式是没有正确结构才能确定该表达式为true或false的表达式.

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(即数字然后为数字)

注意

我尝试使用

Boolean.valueOf(String)

Boolean.valueOf(String)

Boolean.parse(String)

Boolean.parse(String)

其他类型的布尔方法

推荐答案

EDIT 现在将不允许任何表达式成功.

EDIT Will now not allow any expression to be success.

EDIT2 评估示例.

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

docs.oracle/javase/7/docs/api/javax/script/ScriptEngine.html

docs.oracle/javase/7/docs/api/javax/script/ScriptEngineManager.html

更多推荐

Java:构建逻辑表达式,然后对其进行验证

本文发布于:2023-11-12 10:29:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1581228.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对其   表达式   逻辑   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!