简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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