我希望将字符串转换为布尔值,但输出始终为false。
a=true;
b=true;
c=true;
String zOrginal="(a^b)|c";
boolean z= Boolean.parseBoolean(zOrginal);
out.println(z);
输出总是假的,
发布于 2018-06-24 01:04:54
如果要计算表达式"(a^b)|c"
的结果,其中a
、b
和c
是上面定义的变量,只需像其他答案中所述那样直接作为java代码执行表达式即可。
boolean result = (a|b)^c;
然而,如果你真的想要计算一个来自String
的表达式,比如字符串来自用户输入,那么有一个名为JExl的库可以让你这样做:
http://commons.apache.org/proper/commons-jexl/
将以下代码行添加到maven pom.xml
中
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-jexl3</artifactId>
<version>3.1</version>
</dependency>
还没有测试下面的代码,但是你可以试一试。
import org.apache.commons.jexl3.*;
JexlEngine jexl = new JexlBuilder().create();
String expression = "(a|b)^c";
JexlExpression jExpression = jexl.createExpression(expression);
// JexlContext stores the values for variables used in an JexlExpression
JexlContext context = new MapContext();
context.set("a", true);
context.set("b", true);
context.set("c", true);
// evaluate expression.
Long result = (Long) jExpression.evaluate(context);
System.out.println(result); // 0 for false
当然,性能会比直接执行代码差,因为表达式必须解析到抽象语法树(AST)中才能进行计算。
发布于 2018-06-24 00:46:34
这是Boolean.parseBoolean
的源代码
public static boolean parseBoolean(String b)
{
return "true".equalsIgnoreCase(b) ? true : false;
}
此函数唯一返回true
的情况是传递给它的字符串为"true“(尽管大小写)。
如果要检查字符串是否是非空的,请使用String.isEmpty
方法。如果你想真正“评估”字符串,那就不是那么简单了……但是你可能想通读一下Is there an eval() function in Java?。
发布于 2018-06-24 00:47:55
您应该直接计算表达式,而不是在字符串中计算。
boolean a,b,c;
a=true;
b=true;
c=true;
boolean z= (a^b)|c;
System.out.println(z);
https://stackoverflow.com/questions/51003105
复制相似问题