2

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) {
    ...
}
Shane
  • 315
  • 1
  • 5
  • 12
  • 1
    Seems like some more detail is needed: He's not asking to convert `args[0]` to a Boolean from `true` or `false`, he's asking for some method of evaluating `x==y` or some other expression and applying it to `x` and `y` in the application. – Chris Mantle Oct 31 '13 at 11:17
  • @ChrisMantle Check my other answer, i treated what you are saying – Adel Boutros Oct 31 '13 at 11:19

4 Answers4

2

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.

Chris Mantle
  • 6,595
  • 3
  • 34
  • 48
  • 1
    See also the answers to http://stackoverflow.com/questions/4010674/looking-for-an-expression-evaluator – JeremyP Oct 31 '13 at 11:41
1

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

Adel Boutros
  • 10,205
  • 7
  • 55
  • 89
0

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();
...
  • 1
    Again, `args[0]` is *not* a value of `true` or `false` that can be trivially parsed to a `Boolean`. It's an expression that needs evaluating. – Chris Mantle Oct 31 '13 at 11:42
-2

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());
Voidpaw
  • 910
  • 1
  • 5
  • 18