有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

布尔Java:构建逻辑表达式,然后验证它们

我有一个小功能,需要确定用户创建的规则在语法上是否有效

也就是说,我正在构建的结构如下所示:

  • 1==1
  • 1+1==1
  • 1+1==1或1==1
  • 以上示例的更多组合

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

String expression = "";

while(items.hasNext())
{
    String currentItem = items.next();
    expression += currentItem.value();
}

//Check if the expression is valid

有效表达式

有效表达式是具有逻辑运算符(<;、<;=、==、==、=>;、>;)的表达式输出是真是假(不管是哪一个)

  • 1==1
  • 1<;二,
  • 1==1或1<;四,
  • 4==9或9==3

无效表达式

无效表达式是指没有正确结构以确定该表达式是真是假的表达式

  • 一,
  • 1+1
  • 1==
  • ==1
  • 一,
  • 11(先是数字,然后是数字)

注意

我试过使用

Boolean.valueOf(String)

Boolean.parse(String)

Other types of Boolean methods


共 (1) 个答案

  1. # 1 楼答案

    编辑现在不允许任何表达式成功

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

    https://docs.oracle.com/javase/7/docs/api/javax/script/ScriptEngine.html

    https://docs.oracle.com/javase/7/docs/api/javax/script/ScriptEngineManager.html