简体   繁体   English

将字符串转换为数学对象

[英]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? 有没有一种方法可以实现一种方法,该方法可以帮助我针对没有多个if语句的字符串compare参数比较两个int?

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. 没有办法像在Java源代码中那样将字符串当作字符串来应用。 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. 有很多方法可以使您对此非常满意(例如,使用Map<String, Callable<Boolean>> ),但是对于您所描述的内容似乎并不值得。

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. 另外(如CM Kanode和screppedcola在其评论中建议的那样),您可以使用ScriptEngine将表达式评估为JavaScript,但这似乎有点过头了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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