'Evaluate command line argument as boolean expression
I'm trying to take a string, passed as an argument, and evaluate it as a boolean expression in an if conditional statement. For example, the user invokes MyProgram like $ java MyProgram x==y
.
Example Program
Defined variables:
int x;
int y;
Boolean expression argument:
String stringToEval = args[0];
Control program execution with user expression:
if (stringToEval) {
...
}
Solution 1:[1]
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
. You may be able to use something like Janino, JEXL or Jeval to do this. You could also write a small parser yourself, if the inputs are well-defined.
Solution 2:[2]
What you are doing is a bit complexe, you need to evaluate the expression and extract the 2 arguments form the operation
String []arguments = extractFromArgs(args[0])
there you get x
and y
values in arguments
then:
if (arguments [0].equals(arguments[1]))
If x and y are integers:
int intX = new Integer(arguments[0]);
int intY = new Integer(arguments[0]);
if (intX == intY)
etc...
PS: Why use Integer, Double ..? Because in String evaluation "2" is not equal to "2.0" whereas in Integer and Double evaluaiton, they are equal
Solution 3:[3]
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.
For doing this you have to Option either you use valueOf(String s)
or 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();
...
Solution 4:[4]
So from what I understand the string args[0] is a boolean? 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());
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Chris Mantle |
Solution 2 | |
Solution 3 | user2885596 |
Solution 4 | Voidpaw |