简体   繁体   English

(Java)将字符串评估为布尔值

[英](Java) evaluate string as boolean

Ok... I've been searching for a while now, and I can't seem to find a simple solution to this. 好的...我已经搜索了一段时间,但似乎无法找到简单的解决方案。

I'm trying to take a string passed upon invocation and evaluate it as a boolean expression in an IF conditional 我正在尝试获取调用时传递的字符串,并在IF条件中将其评估为布尔表达式

$ java MyProgram x==y $ java MyProgram x == y

...
int x;
int y;
...
String stringToEval = args[0];
...
if(stringToEval){
    printSomething();
} else printNothing();
...

thanks in advance 提前致谢

You'll need to use some form of expression parser to parse the value in args[0] and create an expression that can be applied to x and y . 您需要使用某种形式的表达式解析器来解析args[0]的值,并创建一个可应用于xy的表达式。 You may be able to use something like Janino , JEXL or Jeval to do this. 您可能可以使用JaninoJEXLJeval之类的工具来执行此操作。 You could also write a small parser yourself, if the inputs are well-defined. 如果输入定义明确,您也可以自己编写一个小型解析器。

What you are doing is a bit complexe, you need to evaluate the expression and extract the 2 arguments form the operation 您正在做的事情有点复杂,您需要评估表达式并从操作中提取2个参数

String []arguments = extractFromArgs(args[0])

there you get x and y values in arguments 在那里你得到arguments xy

then: 然后:

if (arguments [0].equals(arguments[1]))

If x and y are integers: 如果x和y是整数:

int intX = new Integer(arguments[0]);
int intY = new Integer(arguments[0]);
if (intX == intY)

etc... 等等...

PS: Why use Integer, Double ..? PS:为什么要使用Integer,Double ..? Because in String evaluation "2" is not equal to "2.0" whereas in Integer and Double evaluaiton, they are equal 因为在String求值中“ 2”不等于“ 2.0”,而在Integer和Double求值中它们相等

What ever you are taking input as a command line argument is the String type and you want to use it as a Boolean so you need to covert a String into a boolean. 您将输入作为命令行参数使用的是String类型,并且想要将其用作布尔值,因此需要将String转换为布尔值。

For doing this you have to Option either you use valueOf(String s) or parseBoolean(String s) 为此,您必须选择使用valueOf(String s)parseBoolean(String s)

so your code must look like this, 因此您的代码必须像这样,

S...
int x;
int y;
...
String stringToEval = args[0];
boolean b = Boolean.valueOf(stringToEval);

boolean b1 = Boolean.parseBoolean(stringToEval); // this also works 
...
if(b){
    printSomething();
} else printNothing();
...

So from what I understand the string args[0] is a boolean? 因此,据我了解,字符串args [0]是布尔值吗? Why not cast it to a boolean then? 那么为什么不将其转换为布尔值呢?

boolean boolToEval = Boolean.parseBoolean(args[0]);
//OR
boolean boolToEval = Boolean.valueOf(args[0]);    

//THEN
(boolToEval ? printSomething() : printSomethingElse());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM