user908015
user908015

Reputation:

Converting a string into a mathematical object

I don't know if this is possible. I'm in a situation where the input is going to look like this:

[int, String, int]

Where the string is either "<", ">", "=", "<=", ">=".

Is there the way to implement a method that would help me compare the two ints with respect to the string compare parameter without multiple if statements?

I hope I've explained it well.

Thanks.

Upvotes: 0

Views: 83

Answers (1)

Ted Hopp
Ted Hopp

Reputation: 234795

There's no way to apply a string as if were an operator in Java source code. You're going to have to test each string value and do the appropriate test.

public boolean eval(int arg1, String op, int arg2) {
    if (op.equals("<")) {
        return arg1 < arg2;
    } else if (op.equals("<=")) {
        return arg1 <= arg2;
    } else . . .
}

There are ways to get very fancy about this (with, for example, a Map<String, Callable<Boolean>>), but it doesn't seem worth it for what you're describing.

Alternatively (as CM Kanode and screppedcola suggest in their comments) you can evaluate an expression as JavaScript, using a ScriptEngine, but this also seems like overkill.

Upvotes: 3

Related Questions