質問

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) {
    ...
}
役に立ちましたか?

解決

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.

他のヒント

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

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();
...

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());
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top