Solved How can i get an calculation form config?

Discussion in 'Spigot Plugin Development' started by Attacler, May 2, 2017.

  1. I did this with help from ystrike099 he said this and it works:

    If you want to calculate a matchematical expression I suggest something like this:
    Code (Text):
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("js");
    Object result = engine.eval("4*5");
    But I don't think it's required tho and it's not very resource-friendly. So I suggest you to try another way, but if you need to calculate it this way, then thank me later ^_^

    Note: This method of calculating is as I said earlier, not very resource-friendly. You are basically loading an entire JavaScript (see "js" above) interpreter to do some math. But it works. See more info here.

    Other alternatives:
    - ExpressionBuiler

    Thanks for reading!

    Bye,
    Bart
     
    #1 Attacler, May 2, 2017
    Last edited: May 3, 2017
  2. Code (Text):
    int ConfigInt = getConfig().getInt("name.of.path");
    Int level = getting level..
    int calc = ConfifInt*level;
     
     
    • Optimistic Optimistic x 1
  3. use getInt instead of getString then just use * operator.
     
    • Agree Agree x 1
    • Optimistic Optimistic x 1
  4. If you want to calculate a matchematical expression I suggest something like this:
    Code (Text):
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("js");
    Object result = engine.eval("4*5");
    But I don't think it's required tho and it's not very resource-friendly. So I suggest you to try another way, but if you need to calculate it this way, then thank me later ^_^

    Note: This method of calculating is as I said earlier, not very resource-friendly. You are basically loading an entire JavaScript (see "js" above) interpreter to do some math. But it works. See more info here.

    Other alternatives:
    - ExpressionBuiler
     
    • Useful Useful x 1
  5. Thanks, it worked!
     
  6. I'd also recommend exp4j - it's much more lightweight and efficient than a JS interpreter (I'm guessing anyway).

    You can get it via Maven like this:

    Code (Text):

            <dependency>
                <groupId>net.objecthunter</groupId>
                <artifactId>exp4j</artifactId>
                <version>0.4.5</version>
                <scope>compile</scope>
            </dependency>
    And use it like this:

    Code (Text):
    Expression expression = new ExpressionBuilder(equation)
                    .variables(inputVariables)
                    .build();

            for (String inputVariable : inputVariables) {
                expression.setVariable(inputVariable, someValue);
            }

    double value = expression.evaluate();
     
    • Like Like x 1